Skip to content

Commit a59cc4c

Browse files
committed
Merge pull request #914 from groyoh/fix_904
Prevent possible duplicated attributes in serializer
2 parents d981ee5 + 5393e5d commit a59cc4c

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

lib/active_model/serializer.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ def self.inherited(base)
3131
def self.attributes(*attrs)
3232
attrs = attrs.first if attrs.first.class == Array
3333
@_attributes.concat attrs
34+
@_attributes.uniq!
3435

3536
attrs.each do |attr|
3637
define_method attr do
@@ -42,7 +43,7 @@ def self.attributes(*attrs)
4243
def self.attribute(attr, options = {})
4344
key = options.fetch(:key, attr)
4445
@_attributes_keys[attr] = {key: key} if key != attr
45-
@_attributes.concat [key]
46+
@_attributes << key unless @_attributes.include?(key)
4647
define_method key do
4748
object.read_attribute_for_serialization(attr)
4849
end unless method_defined?(key) || _fragmented.respond_to?(attr)

test/serializers/attribute_test.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ def test_attribute_inheritance_with_key
2424
adapter = ActiveModel::Serializer::Adapter::Json.new(blog_serializer)
2525
assert_equal({:id=>1, :title=>"AMS Hints"}, adapter.serializable_hash)
2626
end
27+
28+
def test_multiple_calls_with_the_same_attribute
29+
serializer_class = Class.new(ActiveModel::Serializer) do
30+
attribute :title
31+
attribute :title
32+
end
33+
34+
assert_equal([:title], serializer_class._attributes)
35+
end
2736
end
2837
end
2938
end

test/serializers/attributes_test.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,15 @@ def test_attribute_inheritance_with_new_attribute
4949
assert_equal({id: 1, body: "ZOMG!!", date: "2015", likes: nil},
5050
serializer.attributes)
5151
end
52+
53+
def test_multiple_calls_with_the_same_attribute
54+
serializer_class = Class.new(ActiveModel::Serializer) do
55+
attributes :id, :title
56+
attributes :id, :title, :title, :body
57+
end
58+
59+
assert_equal([:id, :title, :body], serializer_class._attributes)
60+
end
5261
end
5362
end
5463
end

0 commit comments

Comments
 (0)