From 2d2094b588c2291b62aa4099c8737c23c3a5dc15 Mon Sep 17 00:00:00 2001 From: Ismael Abreu Date: Sat, 16 Feb 2013 02:06:25 +0000 Subject: [PATCH] changes to be able to specify multiple attributes with keys --- lib/active_model/serializer.rb | 7 ++++++- test/serializer_test.rb | 22 ++++++++++++++++++++++ test/test_fakes.rb | 16 ++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 9d772a1d..576b34e4 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -69,10 +69,15 @@ module ActiveModel class << self # Define attributes to be used in the serialization. def attributes(*attrs) + self._attributes = _attributes.dup attrs.each do |attr| - attribute attr + if Hash === attr + attr.each {|attr_real, key| attribute attr_real, :key => key } + else + attribute attr + end end end diff --git a/test/serializer_test.rb b/test/serializer_test.rb index 9fe10e64..a7483dd7 100644 --- a/test/serializer_test.rb +++ b/test/serializer_test.rb @@ -29,6 +29,28 @@ class SerializerTest < ActiveModel::TestCase }, hash) end + def test_attributes_method_specifying_keys + user = User.new + user_serializer = UserAttributesWithKeySerializer.new(user, :scope => {}) + + hash = user_serializer.as_json + + assert_equal({ + :user_attributes_with_key => { :f_name => "Jose", :l_name => "Valim", :ok => true } + }, hash) + end + + def test_attributes_method_specifying_some_keys + user = User.new + user_serializer = UserAttributesWithSomeKeySerializer.new(user, :scope => {}) + + hash = user_serializer.as_json + + assert_equal({ + :user_attributes_with_some_key => { :first_name => "Jose", :l_name => "Valim", :ok => true } + }, hash) + end + def test_attribute_method_with_name_as_serializer_prefix object = SomeObject.new("something") object_serializer = SomeSerializer.new(object, {}) diff --git a/test/test_fakes.rb b/test/test_fakes.rb index 73d57088..a758f30a 100644 --- a/test/test_fakes.rb +++ b/test/test_fakes.rb @@ -54,6 +54,22 @@ class UserSerializer < ActiveModel::Serializer end end +class UserAttributesWithKeySerializer < ActiveModel::Serializer + attributes :first_name => :f_name, :last_name => :l_name + + def serializable_hash + attributes.merge(:ok => true).merge(options[:scope]) + end +end + +class UserAttributesWithSomeKeySerializer < ActiveModel::Serializer + attributes :first_name, :last_name => :l_name + + def serializable_hash + attributes.merge(:ok => true).merge(options[:scope]) + end +end + class DefaultUserSerializer < ActiveModel::Serializer attributes :first_name, :last_name end