From f762cf05a55b827684b756f6affdcd54923003c0 Mon Sep 17 00:00:00 2001 From: Andrew White Date: Wed, 2 Nov 2016 11:40:46 +0000 Subject: Fix AS::OrderHash#select and #reject on Ruby 2.1.1+ In Ruby 2.1.1 and later select and reject return a new instance of Hash rather than the subclass so we need to override them to return an instance of the correct class. --- activesupport/lib/active_support/ordered_hash.rb | 14 ++++++++++++++ activesupport/test/ordered_hash_test.rb | 4 ++++ 2 files changed, 18 insertions(+) diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index b0d4f2bd86..e81bd013b6 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -52,6 +52,20 @@ module ActiveSupport true end + if RUBY_VERSION > '2.1.0' + # On Ruby 2.1.1 and later the behavior of .select and reject changed to + # return a new Hash instance so we need to override them to return an + # instance of the correct class. + + def select(*args, &block) + dup.tap { |hash| hash.select!(*args, &block) } + end + + def reject(*args, &block) + dup.tap { |hash| hash.reject!(*args, &block) } + end + end + # Hash is ordered in Ruby 1.9! if RUBY_VERSION < '1.9' diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index a7fd9402c8..bbaccf2594 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -125,6 +125,9 @@ class OrderedHashTest < Test::Unit::TestCase def test_select assert_equal @keys, @ordered_hash.select { true }.map(&:first) + new_ordered_hash = @ordered_hash.select { true } + assert_equal @keys, new_ordered_hash.map(&:first) + assert_instance_of ActiveSupport::OrderedHash, new_ordered_hash end def test_delete_if @@ -147,6 +150,7 @@ class OrderedHashTest < Test::Unit::TestCase assert_equal copy, @ordered_hash assert !new_ordered_hash.keys.include?('pink') assert @ordered_hash.keys.include?('pink') + assert_instance_of ActiveSupport::OrderedHash, new_ordered_hash end def test_clear -- cgit v1.2.3