From a900d31041dd8aea735416087636c0ddbe7cf37d Mon Sep 17 00:00:00 2001 From: vanstee Date: Mon, 8 Apr 2013 20:21:57 -0400 Subject: [PATCH] Support strings as attribute names When generating the `_fast_attributes` method, attribute names that could not be represented as symbols (at least without escaping) would throw parsing errors. --- lib/active_model/serializer.rb | 2 +- test/serializer_test.rb | 11 +++++++++++ test/test_fakes.rb | 8 ++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 2dc4366e..19283f77 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -451,7 +451,7 @@ module ActiveModel method << " h = {}\n" _attributes.each do |name,key| - method << " h[:#{key}] = read_attribute_for_serialization(:#{name}) if send #{INCLUDE_METHODS[name].inspect}\n" + method << " h[:\"#{key}\"] = read_attribute_for_serialization(:\"#{name}\") if send #{INCLUDE_METHODS[name].inspect}\n" end method << " h\nend" diff --git a/test/serializer_test.rb b/test/serializer_test.rb index b45e270c..9573a372 100644 --- a/test/serializer_test.rb +++ b/test/serializer_test.rb @@ -51,6 +51,17 @@ class SerializerTest < ActiveModel::TestCase }, hash) end + def test_attributes_method_with_unsymbolizable_key + user = User.new + user_serializer = UserAttributesWithUnsymbolizableKeySerializer.new(user, :scope => {}) + + hash = user_serializer.as_json + + assert_equal({ + :user_attributes_with_unsymbolizable_key => { :first_name => "Jose", :"last-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 a758f30a..da5097d5 100644 --- a/test/test_fakes.rb +++ b/test/test_fakes.rb @@ -70,6 +70,14 @@ class UserAttributesWithSomeKeySerializer < ActiveModel::Serializer end end +class UserAttributesWithUnsymbolizableKeySerializer < ActiveModel::Serializer + attributes :first_name, :last_name => :"last-name" + + def serializable_hash + attributes.merge(:ok => true).merge(options[:scope]) + end +end + class DefaultUserSerializer < ActiveModel::Serializer attributes :first_name, :last_name end