Skip to content

Commit

Permalink
allow id attribute to be overriden
Browse files Browse the repository at this point in the history
  • Loading branch information
lanej committed Aug 4, 2015
1 parent c4af610 commit f6e3d4e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/active_model/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,12 @@ def self.attribute(attr, options = {})
key = options.fetch(:key, attr)
@_attributes_keys[attr] = { key: key } if key != attr
@_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)

unless respond_to?(key, false) || _fragmented.respond_to?(attr)
define_method key do
object.read_attribute_for_serialization(attr)
end
end
end

def self.fragmented(serializer)
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 @@ -33,6 +33,15 @@ def test_multiple_calls_with_the_same_attribute

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

def test_id_attribute_override
serializer = Class.new(ActiveModel::Serializer) do
attribute :name, key: :id
end

adapter = ActiveModel::Serializer::Adapter::Json.new(serializer.new(@blog))
assert_equal({ blog: { id: "AMS Hints" } }, adapter.serializable_hash)
end
end
end
end

0 comments on commit f6e3d4e

Please sign in to comment.