From 62097edb80226e277fd5a6dd496aa90999202063 Mon Sep 17 00:00:00 2001 From: Sam Pohlenz Date: Tue, 18 May 2010 17:08:26 +0930 Subject: [PATCH] Duplicate and clear hash on #slice. This fixes JSON serialization of ActiveModel::Errors, when :only is included in the options. --- .../serializeration/json_serialization_test.rb | 10 ++++++++++ .../lib/active_support/core_ext/hash/slice.rb | 2 +- 2 files changed, 11 insertions(+), 1 deletions(-) diff --git a/activemodel/test/cases/serializeration/json_serialization_test.rb b/activemodel/test/cases/serializeration/json_serialization_test.rb index 7e89815..fb86e38 100644 --- a/activemodel/test/cases/serializeration/json_serialization_test.rb +++ b/activemodel/test/cases/serializeration/json_serialization_test.rb @@ -96,4 +96,14 @@ class JsonSerializationTest < ActiveModel::TestCase assert_match %r{"label":"Has cheezburger"}, methods_json assert_match %r{"favorite_quote":"Constraints are liberating"}, methods_json end + + test "ActiveModel::Errors should be serializable with only" do + errors = ActiveModel::Errors.new(Contact) + errors.add(:name, "can't be blank") + errors.add(:age, "must be over 18") + + errors_json = ActiveSupport::JSON.encode(errors, :only => :name) + assert_match %r{"name":\["can't be blank"\]}, errors_json + assert_no_match %r{"age":}, errors_json + end end diff --git a/activesupport/lib/active_support/core_ext/hash/slice.rb b/activesupport/lib/active_support/core_ext/hash/slice.rb index e4a864c..2e50585 100644 --- a/activesupport/lib/active_support/core_ext/hash/slice.rb +++ b/activesupport/lib/active_support/core_ext/hash/slice.rb @@ -14,7 +14,7 @@ class Hash # search(options.slice(*valid_keys)) def slice(*keys) keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key) - hash = self.class.new + hash = dup.clear keys.each { |k| hash[k] = self[k] if has_key?(k) } hash end -- 1.7.0.6