mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
Implement ArraySerializer
This commit is contained in:
19
lib/active_model/array_serializer.rb
Normal file
19
lib/active_model/array_serializer.rb
Normal file
@@ -0,0 +1,19 @@
|
||||
module ActiveModel
|
||||
class ArraySerializer
|
||||
def initialize(object, options={})
|
||||
@object = object
|
||||
@options = options
|
||||
end
|
||||
|
||||
def serializable_array
|
||||
@object.map do |item|
|
||||
if serializer = Serializer.serializer_for(item)
|
||||
serializer.new(item).serializable_object(@options.merge(root: nil))
|
||||
else
|
||||
item.as_json
|
||||
end
|
||||
end
|
||||
end
|
||||
alias serializable_object serializable_array
|
||||
end
|
||||
end
|
||||
@@ -9,7 +9,11 @@ module ActiveModel
|
||||
end
|
||||
|
||||
def serializer_for(resource)
|
||||
"#{resource.class.name}Serializer".safe_constantize
|
||||
if resource.respond_to?(:to_ary)
|
||||
ArraySerializer
|
||||
else
|
||||
"#{resource.class.name}Serializer".safe_constantize
|
||||
end
|
||||
end
|
||||
|
||||
attr_accessor :_root, :_attributes, :_associations
|
||||
@@ -114,6 +118,7 @@ module ActiveModel
|
||||
hash = attributes
|
||||
hash.merge! associations
|
||||
end
|
||||
alias serializable_object serializable_hash
|
||||
|
||||
def as_json(options={})
|
||||
if root = options[:root] || self.root
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
require 'active_model'
|
||||
require 'active_model/serializer'
|
||||
require 'active_model/array_serializer'
|
||||
|
||||
begin
|
||||
require 'action_controller'
|
||||
|
||||
Reference in New Issue
Block a user