aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--activesupport/lib/active_support/core_ext/hash/slice.rb5
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb21
2 files changed, 26 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/core_ext/hash/slice.rb b/activesupport/lib/active_support/core_ext/hash/slice.rb
index be4dec6e53..3f14470f36 100644
--- a/activesupport/lib/active_support/core_ext/hash/slice.rb
+++ b/activesupport/lib/active_support/core_ext/hash/slice.rb
@@ -9,6 +9,11 @@ module ActiveSupport #:nodoc:
# end
#
# search(options.slice(:mass, :velocity, :time))
+ #
+ # If you have an array of keys you want to limit to, you should splat them:
+ #
+ # valid_keys = [:mass, :velocity, :time]
+ # search(options.slice(*valid_keys))
module Slice
# Returns a new hash with only the given keys.
def slice(*keys)
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index 2ab7681a8a..fc8ed45358 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -292,6 +292,27 @@ class HashExtTest < Test::Unit::TestCase
assert_equal expected, original
end
+ def test_slice_with_an_array_key
+ original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
+ expected = { [:a, :b] => "an array key", :c => 10 }
+
+ # Should return a new hash with only the given keys when given an array key.
+ assert_equal expected, original.slice([:a, :b], :c)
+ assert_not_equal expected, original
+
+ # Should replace the hash with only the given keys when given an array key.
+ assert_equal expected, original.slice!([:a, :b], :c)
+ assert_equal expected, original
+ end
+
+ def test_slice_with_splatted_keys
+ original = { :a => 'x', :b => 'y', :c => 10, [:a, :b] => "an array key" }
+ expected = { :a => 'x', :b => "y" }
+
+ # Should grab each of the splatted keys.
+ assert_equal expected, original.slice(*[:a, :b])
+ end
+
def test_indifferent_slice
original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access
expected = { :a => 'x', :b => 'y' }.with_indifferent_access