This commit is contained in:
Aaron Renoir
2014-10-26 13:04:14 -07:00
parent 47deb87e81
commit 39bee48ae6
7 changed files with 113 additions and 3 deletions

View File

@@ -124,7 +124,14 @@ module ActiveModel
end
def attributes(options = {})
self.class._attributes.dup.each_with_object({}) do |name, hash|
attributes =
if options[:fields]
self.class._attributes & options[:fields]
else
self.class._attributes.dup
end
attributes.each_with_object({}) do |name, hash|
hash[name] = send(name)
end
end

View File

@@ -17,6 +17,7 @@ module ActiveModel
end
def to_json(options = {})
options[:fieldset] = ActiveModel::Serializer::Fieldset.new(serializer, options[:fields])
serializable_hash(options).to_json
end
end

View File

@@ -10,9 +10,12 @@ module ActiveModel
def serializable_hash(options = {})
@root = (options[:root] || serializer.json_key).to_s.pluralize.to_sym
@hash = {}
@fieldset = options[:fieldset]
if serializer.respond_to?(:each)
@hash[@root] = serializer.map{|s| self.class.new(s).serializable_hash[@root] }
opt = @fieldset ? {fieldset: @fieldset} : {}
@hash[@root] = serializer.map{|s| self.class.new(s).serializable_hash(opt)[@root] }
else
@hash[@root] = attributes_for_serializer(serializer, {})
@@ -57,6 +60,11 @@ module ActiveModel
private
def attributes_for_serializer(serializer, options)
if fields = @fieldset && @fieldset.fields_for(serializer)
options[:fields] = fields
end
attributes = serializer.attributes(options)
attributes[:id] = attributes[:id].to_s if attributes[:id]
attributes

View File

@@ -0,0 +1,33 @@
module ActiveModel
class Serializer
class Fieldset
attr_accessor :fields, :root
def initialize(serializer, fields = {})
@root = serializer.json_key
@fields = parse(fields)
end
def fields_for(serializer)
key = serializer.json_key || serializer.class.root_name
fields[key]
end
private
def parse(fields)
if fields.is_a?(Hash)
fields.inject({}) { |h,(k,v)| h[k.to_s] = v.map(&:to_sym); h}
elsif fields.is_a?(Array)
hash = {}
hash[root.to_s] = fields.map(&:to_sym)
hash
else
{}
end
end
end
end
end