diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 1208ca80..ef68072c 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -103,7 +103,7 @@ module ActiveModel end class_attribute :_attributes - self._attributes = Set.new + self._attributes = {} class_attribute :_associations self._associations = [] @@ -116,7 +116,15 @@ module ActiveModel class << self # Define attributes to be used in the serialization. def attributes(*attrs) - self._attributes += attrs + self._attributes = _attributes.dup + + attrs.each do |attr| + self._attributes[attr] = attr + end + end + + def attribute(attr, options={}) + self._attributes = _attributes.merge(attr => options[:key] || attr) end def associate(klass, attrs) #:nodoc: @@ -192,9 +200,9 @@ module ActiveModel klass = model_class columns = klass.columns_hash - attrs = _attributes.inject({}) do |hash, name| + attrs = _attributes.inject({}) do |hash, (name,key)| column = columns[name] - hash.merge name => column[:type] + hash.merge key => column[:type] end associations = _associations.inject({}) do |hash, association| @@ -299,8 +307,8 @@ module ActiveModel def attributes hash = {} - _attributes.each do |name| - hash[name] = @object.read_attribute_for_serialization(name) + _attributes.each do |name,key| + hash[key] = @object.read_attribute_for_serialization(name) end hash diff --git a/test/serializer_test.rb b/test/serializer_test.rb index b790f23e..ae2b7e76 100644 --- a/test/serializer_test.rb +++ b/test/serializer_test.rb @@ -509,6 +509,26 @@ class SerializerTest < ActiveModel::TestCase }, serializer.as_json) end + def test_attribute_key + serializer_class = Class.new(ActiveModel::Serializer) do + root :user + + attribute :first_name, :key => :firstName + attribute :last_name, :key => :lastName + attribute :password + end + + serializer = serializer_class.new(User.new, nil) + + assert_equal({ + :user => { + :firstName => "Jose", + :lastName => "Valim", + :password => "oh noes yugive my password" + } + }, serializer.as_json) + end + def setup_model Class.new do class << self