Merge pull request #679 from Ahalogy/serializer-options

Serializer options
This commit is contained in:
Steve Klabnik 2014-10-14 11:37:47 -04:00
commit 89f87bf855
4 changed files with 31 additions and 6 deletions

View File

@ -38,9 +38,9 @@ module ActiveModel
serializer_class.new(item, scope: scope, key_format: key_format, only: @only, except: @except, polymorphic: @polymorphic, namespace: @namespace)
end
def serializable_object
def serializable_object(options={})
@object.map do |item|
serializer_for(item).serializable_object_with_notification
serializer_for(item).serializable_object_with_notification(options)
end
end
alias_method :serializable_array, :serializable_object

View File

@ -9,18 +9,18 @@ module ActiveModel
def as_json(options={})
instrument('!serialize') do
if root = options.fetch(:root, json_key)
hash = { root => serializable_object }
hash = { root => serializable_object(options) }
hash.merge!(serializable_data)
hash
else
serializable_object
serializable_object(options)
end
end
end
def serializable_object_with_notification
def serializable_object_with_notification(options={})
instrument('!serialize') do
serializable_object
serializable_object(options)
end
end

View File

@ -273,7 +273,13 @@ end
end]
end
attr_writer :serialization_options
def serialization_options
@serialization_options || {}
end
def serializable_object(options={})
self.serialization_options = options
return @wrap_in_array ? [] : nil if @object.nil?
hash = attributes
hash.merge! associations

View File

@ -11,5 +11,24 @@ module ActiveModel
assert_equal({foo: :bar}, @serializer.context)
end
end
class SerializationOptionsTest < Minitest::Test
def setup
@profile = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' })
@profile_serializer = ProfileSerializer.new(@profile)
@profile_serializer.instance_eval do
def description
serialization_options[:force_the_description]
end
end
end
def test_filtered_attributes_serialization
forced_description = "This is a test"
assert_equal({
'profile' => { name: 'Name 1', description: forced_description }
}, @profile_serializer.as_json(force_the_description: forced_description))
end
end
end
end