Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save christhekeele/f9e4d8f74296c8d8924a to your computer and use it in GitHub Desktop.
Save christhekeele/f9e4d8f74296c8d8924a to your computer and use it in GitHub Desktop.
A monkey patch to ActiveModel::Serializers 0.9.0.alpha1 to add contextual awareness of nesting and listing.
require 'active_model/serializer/associations'
module ActiveModel
class Serializer
def initialize(object, options={})
@object = object
@scope = options[:scope]
@root = options.fetch(:root, self.class._root)
@meta_key = options[:meta_key] || :meta
@meta = options[@meta_key]
@wrap_in_array = options[:_wrap_in_array]
@only = Array(options[:only]) if options[:only]
@except = Array(options[:except]) if options[:except]
@key_format = options[:key_format]
# Watch for predicate options.
@associated = options[:associated] || false
@listed = options[:listed] || false
end
def listed?
@listed
end
def associated?
@associated
end
def nested?
listed? or associated?
end
class Association
# Force all objects serialized as an association
# to recognize they're nested.
def build_serializer(object, options = {})
serializer_class(object).new(object, options.merge(self.options).merge(associated: true))
end
end
end
end
require 'active_model/array_serializer'
module ActiveModel
class ArraySerializer
# Force all objects serialized as an array
# to recognize they're listed.
def serializer_for(item)
serializer_class = @each_serializer || Serializer.serializer_for(item) || DefaultSerializer
serializer_class.new(item, scope: scope, listed: true)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment