Allow to pass options to associations

Closes #331
This commit is contained in:
Santiago Pastorino 2014-01-02 19:56:06 -02:00
parent 67c550f2ee
commit c8cfe94f29
3 changed files with 16 additions and 2 deletions

View File

@ -107,7 +107,7 @@ end
@root = options.fetch(:root, self.class._root) @root = options.fetch(:root, self.class._root)
@meta_key = options[:meta_key] || :meta @meta_key = options[:meta_key] || :meta
@meta = options[@meta_key] @meta = options[@meta_key]
@options = options.reject{|k,v| [:scope, :root, :meta_key, :meta].include?(k) } @options = options.reject{|k,v| [:root, :meta_key, :meta].include?(k) }
end end
attr_accessor :object, :scope, :meta_key, :meta, :root, :options attr_accessor :object, :scope, :meta_key, :meta, :root, :options
@ -166,7 +166,7 @@ end
def build_serializer(association) def build_serializer(association)
object = send(association.name) object = send(association.name)
association.build_serializer(object, scope: scope) association.build_serializer(object, options)
end end
def serialize(association) def serialize(association)

View File

@ -50,6 +50,11 @@ class ProfileSerializer < ActiveModel::Serializer
scope ? "#{description} - #{scope}" : description scope ? "#{description} - #{scope}" : description
end end
def name
name = object.read_attribute_for_serialization(:name)
options[:custom_name] ? "#{name} - #{options[:custom_name]}" : name
end
attributes :name, :description attributes :name, :description
end end

View File

@ -62,6 +62,15 @@ module ActiveModel
}, @user_serializer.as_json) }, @user_serializer.as_json)
end end
def test_allow_to_pass_options_to_associations
@user_serializer.options.merge!(custom_name: 'custom')
@association.embed = :objects
assert_equal({
'user' => { name: 'Name 1', email: 'mail@server.com', profile: { name: 'N1 - custom', description: 'D1' } }
}, @user_serializer.as_json)
end
def test_associations_embedding_nil_ids_serialization_using_as_json def test_associations_embedding_nil_ids_serialization_using_as_json
@association.embed = :ids @association.embed = :ids
@user.instance_eval do @user.instance_eval do