Created
January 20, 2015 00:59
-
-
Save warp/06bd8238369c1fd70da6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for active model serializers 0.10.0