Skip to content

Instantly share code, notes, and snippets.

@warp
Created January 20, 2015 00:59
Show Gist options
  • Save warp/06bd8238369c1fd70da6 to your computer and use it in GitHub Desktop.
Save warp/06bd8238369c1fd70da6 to your computer and use it in GitHub Desktop.
module ActiveModel
class Serializer
class Adapter
class JsonFieldsets < Adapter
def initialize(serializer, options = {})
super
if fields = options.delete(:fields)
@fieldset = fields.split(',').map(&:to_sym)
else
@fieldset = options[:fieldset]
end
end
def serializable_hash(options = {})
if serializer.respond_to?(:each)
@result = serializer.map{|s| self.class.new(s, options.merge(fieldset: @fieldset)).serializable_hash }
else
options[:fields] = @fieldset
@result = serializer.attributes(options)
serializer.each_association do |name, association, opts|
if association.respond_to?(:each)
array_serializer = association
@result[name] = array_serializer.map { |item| item.attributes(opts) }
else
if association
@result[name] = association.attributes(options)
else
@result[name] = nil
end
end
end
end
if root = options.fetch(:root, serializer.json_key)
@result = { root => @result }
end
@result
end
end
end
end
end
ActiveModel::Serializer.config.adapter = ActiveModel::Serializer::Adapter::JsonFieldsets
@warp
Copy link
Author

warp commented Jan 20, 2015

for active model serializers 0.10.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment