mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-24 23:06:50 +00:00
Merge pull request #11 from Adman65/has_many-implicit-serializer
Has many implicit serializer
This commit is contained in:
commit
03f08a8351
@ -134,12 +134,9 @@ module ActiveModel
|
|||||||
class_eval "def #{attr}() object.#{attr} end", __FILE__, __LINE__
|
class_eval "def #{attr}() object.#{attr} end", __FILE__, __LINE__
|
||||||
end
|
end
|
||||||
|
|
||||||
# if :key is specified without :serializer, then use conventions
|
options[:serializer] ||= begin
|
||||||
# to determine the serializer
|
serializer_class = (options[:key] || attr).to_s.classify
|
||||||
if options[:key] && !options[:serializer]
|
const_get("#{serializer_class}Serializer")
|
||||||
options[:serializer] = const_get("#{options[:key].to_s.camelize.singularize}Serializer")
|
|
||||||
else
|
|
||||||
options[:serializer] ||= const_get("#{attr.to_s.camelize}Serializer")
|
|
||||||
end
|
end
|
||||||
|
|
||||||
klass.new(attr, options)
|
klass.new(attr, options)
|
||||||
|
|||||||
@ -211,6 +211,30 @@ class SerializerTest < ActiveModel::TestCase
|
|||||||
}, json)
|
}, json)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_implicit_serializer_for_has_many
|
||||||
|
blog_with_posts = Class.new(Blog) do
|
||||||
|
attr_accessor :posts
|
||||||
|
end
|
||||||
|
|
||||||
|
blog_serializer = Class.new(ActiveModel::Serializer) do
|
||||||
|
const_set(:PostSerializer, PostSerializer)
|
||||||
|
has_many :posts
|
||||||
|
end
|
||||||
|
|
||||||
|
user = User.new
|
||||||
|
blog = blog_with_posts.new
|
||||||
|
blog.posts = [Post.new(:title => 'test')]
|
||||||
|
|
||||||
|
json = blog_serializer.new(blog, user).as_json
|
||||||
|
assert_equal({
|
||||||
|
:posts => [{
|
||||||
|
:title => "test",
|
||||||
|
:body => nil,
|
||||||
|
:comments => []
|
||||||
|
}]
|
||||||
|
}, json)
|
||||||
|
end
|
||||||
|
|
||||||
def test_overridden_associations
|
def test_overridden_associations
|
||||||
author_serializer = Class.new(ActiveModel::Serializer) do
|
author_serializer = Class.new(ActiveModel::Serializer) do
|
||||||
attributes :first_name
|
attributes :first_name
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user