mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 15:23:06 +00:00
implement sparse fieldsets http://jsonapi.org/format/#fetching-sparse-fieldsets
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
33
lib/active_model/serializer/fieldset.rb
Normal file
33
lib/active_model/serializer/fieldset.rb
Normal 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
|
||||
Reference in New Issue
Block a user