Skip to content

Instantly share code, notes, and snippets.

@skwp
Created January 23, 2015 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skwp/5afe7b2a238260f301ac to your computer and use it in GitHub Desktop.
Save skwp/5afe7b2a238260f301ac to your computer and use it in GitHub Desktop.
roar_nil_defaults.rb
require 'roar/decorator'
# Ok..get ready for a fun one:
#
# We use Roar::Decorator to serialize into our search engine (ElasticSearch)
# Example: app/reverb/search/serializers/product.rb
#
# When we serialize fields that are false or nil (booleans), they are omitted
# from the json by default.
#
# When we later pull back the results and try to decorate them
# Example: app/decorators/feed_listing_decorator.rb
#
# The DelegateClass used will blow up with method missing issues if the method
# in question is not defined. For example 'shipping_local' on Product which is
# a boolean, and false by default, is omitted from json, thus omitted from ES
# and the resulting decorator will blow up when the 'shipping_local' method is
# invoked.
#
# To combat this and force all attributes into the json regardless of them
# being nil, Roar does support a 'render_nil' option. However it does _not_
# support setting this option on by default, thus we would have to do something
# like this absolutely everywhere to ensure the bug doesn't hit:
#
# property :foo, render_nil: true
#
# There's an open issue on Representable already for supporting global defaults:
# https://github.com/apotonick/representable/issues/43
#
# This solution monkeypatches the class in order to set the property to be the default.
Roar::Decorator.class_eval do
def self.property(name, options={})
super(name, options.merge!(render_nil: true))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment