Add support for overriding associations, mostly used for authorization

This commit is contained in:
Jose and Yehuda 2011-10-15 17:01:08 +02:00
parent 776da539d7
commit 22c322f056
2 changed files with 31 additions and 1 deletions

View File

@ -41,6 +41,10 @@ module ActiveModel
def associate(klass, attrs)
options = attrs.extract_options!
self._associations += attrs.map do |attr|
unless method_defined?(attr)
class_eval "def #{attr}() object.#{attr} end", __FILE__, __LINE__
end
options[:serializer] ||= const_get("#{attr.to_s.camelize}Serializer")
klass.new(attr, options)
end
@ -79,7 +83,7 @@ module ActiveModel
hash = attributes
_associations.each do |association|
associated_object = object.send(association.name)
associated_object = send(association.name)
hash[association.name] = association.serialize(associated_object, scope)
end

View File

@ -174,4 +174,30 @@ class SerializerTest < ActiveModel::TestCase
}
}, json)
end
def test_overridden_associations
author_serializer = Class.new(ActiveModel::Serializer) do
attributes :first_name
end
blog_serializer = Class.new(ActiveModel::Serializer) do
const_set(:PersonSerializer, author_serializer)
has_one :person
def person
object.author
end
end
user = User.new
blog = Blog.new
blog.author = user
json = blog_serializer.new(blog, user).as_json
assert_equal({
:person => {
:first_name => "Jose"
}
}, json)
end
end