From f6e3d4e1f96275a090222896c168afe3423d0200 Mon Sep 17 00:00:00 2001 From: Josh Lane Date: Tue, 4 Aug 2015 09:22:05 -0700 Subject: [PATCH] allow id attribute to be overriden --- lib/active_model/serializer.rb | 9 ++++++--- test/serializers/attribute_test.rb | 9 +++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index c267e5f0f..e31081968 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -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) diff --git a/test/serializers/attribute_test.rb b/test/serializers/attribute_test.rb index c945a8fc2..d545a60ec 100644 --- a/test/serializers/attribute_test.rb +++ b/test/serializers/attribute_test.rb @@ -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