aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel
diff options
context:
space:
mode:
authorJose and Yehuda <wycats@gmail.com>2011-10-15 17:01:08 +0200
committerJose and Yehuda <wycats@gmail.com>2011-10-15 18:40:38 +0200
commit22c322f056f42d95b0421e6608f404134463de13 (patch)
treec35a15a73d606750a8ac57f8f18c330bbb1e5e2b /activemodel
parent776da539d72c98d077f97789a1265dd23a79711f (diff)
downloadrails-22c322f056f42d95b0421e6608f404134463de13.tar.gz
rails-22c322f056f42d95b0421e6608f404134463de13.tar.bz2
rails-22c322f056f42d95b0421e6608f404134463de13.zip
Add support for overriding associations, mostly used for authorization
Diffstat (limited to 'activemodel')
-rw-r--r--activemodel/lib/active_model/serializer.rb6
-rw-r--r--activemodel/test/cases/serializer_test.rb26
2 files changed, 31 insertions, 1 deletions
diff --git a/activemodel/lib/active_model/serializer.rb b/activemodel/lib/active_model/serializer.rb
index c5b433df51..6e89eec09c 100644
--- a/activemodel/lib/active_model/serializer.rb
+++ b/activemodel/lib/active_model/serializer.rb
@@ -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
diff --git a/activemodel/test/cases/serializer_test.rb b/activemodel/test/cases/serializer_test.rb
index 37a675bc20..08dd73e03b 100644
--- a/activemodel/test/cases/serializer_test.rb
+++ b/activemodel/test/cases/serializer_test.rb
@@ -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