Serializers now inherit attributes

This commit is contained in:
Yohan Robert 2015-04-08 16:51:28 +02:00 committed by groyoh
parent 1577969cb7
commit 02ffff599f
4 changed files with 57 additions and 4 deletions

View File

@ -22,9 +22,9 @@ module ActiveModel
end
def self.inherited(base)
base._attributes = []
base._attributes_keys = {}
base._associations = {}
base._attributes = self._attributes.try(:dup) || []
base._attributes_keys = self._attributes_keys.try(:dup) || {}
base._associations = self._associations.try(:dup) || {}
base._urls = []
end

View File

@ -101,6 +101,27 @@ module ActiveModel
assert blog_is_present
end
def test_associations_inheritance
inherited_klass = Class.new(PostSerializer)
assert_equal(PostSerializer._associations, inherited_klass._associations)
end
def test_associations_inheritance_with_new_association
inherited_klass = Class.new(PostSerializer) do
has_many :top_comments, serializer: CommentSerializer
end
expected_associations = PostSerializer._associations.merge(
top_comments: {
type: :has_many,
association_options: {
serializer: CommentSerializer
}
}
)
assert_equal(inherited_klass._associations, expected_associations)
end
end
end
end

View File

@ -17,7 +17,13 @@ module ActiveModel
adapter = ActiveModel::Serializer::Adapter::Json.new(@blog_serializer)
assert_equal({:id=>1, :title=>"AMS Hints"}, adapter.serializable_hash)
end
def test_attribute_inheritance_with_key
inherited_klass = Class.new(AlternateBlogSerializer)
blog_serializer = inherited_klass.new(@blog)
adapter = ActiveModel::Serializer::Adapter::Json.new(blog_serializer)
assert_equal({:id=>1, :title=>"AMS Hints"}, adapter.serializable_hash)
end
end
end
end

View File

@ -6,6 +6,11 @@ module ActiveModel
def setup
@profile = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' })
@profile_serializer = ProfileSerializer.new(@profile)
@comment = Comment.new(id: 1, body: "ZOMG!!", date: "2015")
@serializer_klass = Class.new(CommentSerializer)
@serializer_klass_with_new_attributes = Class.new(CommentSerializer) do
attributes :date, :likes
end
end
def test_attributes_definition
@ -23,6 +28,27 @@ module ActiveModel
@profile_serializer.attributes(fields: [:name, :description], required_fields: [:name]))
end
def test_attributes_inheritance_definition
assert_equal([:id, :body], @serializer_klass._attributes)
end
def test_attributes_inheritance
serializer = @serializer_klass.new(@comment)
assert_equal({id: 1, body: "ZOMG!!"},
serializer.attributes)
end
def test_attribute_inheritance_with_new_attribute_definition
assert_equal([:id, :body, :date, :likes], @serializer_klass_with_new_attributes._attributes)
assert_equal([:id, :body], CommentSerializer._attributes)
end
def test_attribute_inheritance_with_new_attribute
serializer = @serializer_klass_with_new_attributes.new(@comment)
assert_equal({id: 1, body: "ZOMG!!", date: "2015", likes: nil},
serializer.attributes)
end
end
end
end