Skip to content

Commit

Permalink
Merge pull request rails-api#914 from groyoh/fix_904
Browse files Browse the repository at this point in the history
Prevent possible duplicated attributes in serializer
  • Loading branch information
joaomdmoura committed May 18, 2015
2 parents d981ee5 + 5393e5d commit a59cc4c
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/active_model/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def self.inherited(base)
def self.attributes(*attrs)
attrs = attrs.first if attrs.first.class == Array
@_attributes.concat attrs
@_attributes.uniq!

attrs.each do |attr|
define_method attr do
Expand All @@ -42,7 +43,7 @@ def self.attributes(*attrs)
def self.attribute(attr, options = {})
key = options.fetch(:key, attr)
@_attributes_keys[attr] = {key: key} if key != attr
@_attributes.concat [key]
@_attributes << key unless @_attributes.include?(key)
define_method key do
object.read_attribute_for_serialization(attr)
end unless method_defined?(key) || _fragmented.respond_to?(attr)
Expand Down
9 changes: 9 additions & 0 deletions test/serializers/attribute_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ def test_attribute_inheritance_with_key
adapter = ActiveModel::Serializer::Adapter::Json.new(blog_serializer)
assert_equal({:id=>1, :title=>"AMS Hints"}, adapter.serializable_hash)
end

def test_multiple_calls_with_the_same_attribute
serializer_class = Class.new(ActiveModel::Serializer) do
attribute :title
attribute :title
end

assert_equal([:title], serializer_class._attributes)
end
end
end
end
9 changes: 9 additions & 0 deletions test/serializers/attributes_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@ def test_attribute_inheritance_with_new_attribute
assert_equal({id: 1, body: "ZOMG!!", date: "2015", likes: nil},
serializer.attributes)
end

def test_multiple_calls_with_the_same_attribute
serializer_class = Class.new(ActiveModel::Serializer) do
attributes :id, :title
attributes :id, :title, :title, :body
end

assert_equal([:id, :title, :body], serializer_class._attributes)
end
end
end
end

0 comments on commit a59cc4c

Please sign in to comment.