Ticket #7369: hash-without.diff
| File hash-without.diff, 2.5 kB (added by eventualbuddha, 2 years ago) |
|---|
-
activesupport/lib/active_support/core_ext/hash/slice.rb
old new 11 11 # end 12 12 # 13 13 # search(options.slice(:mass, :velocity, :time)) 14 # 15 # Also allows leaving out certain keys. This is useful when duplicating 16 # a hash but omitting a certain subset: 17 # 18 # Event.new(event.attributes.without(:id, :user_id)) 14 19 module Slice 15 20 # Returns a new hash with only the given keys. 16 21 def slice(*keys) … … 22 27 def slice!(*keys) 23 28 replace(slice(*keys)) 24 29 end 30 31 # Returns a new hash without the given keys. 32 def without(*keys) 33 allowed = self.keys - (respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys) 34 slice(*allowed) 35 end 36 37 # Replaces the hash without the given keys. 38 def without!(*keys) 39 replace(without(*keys)) 40 end 25 41 end 26 42 end 27 43 end -
activesupport/test/core_ext/hash_ext_test.rb
old new 272 272 assert_equal expected, copy 273 273 end 274 274 end 275 276 def test_without 277 original = { :a => 'x', :b => 'y', :c => 10 } 278 expected = { :a => 'x' } 279 280 # Should return a hash without the given keys. 281 assert_equal expected, original.without(:b, :c) 282 assert_not_equal expected, original 283 284 # Should ignore non-existant keys. 285 assert_equal expected, original.without(:b, :c, :d) 286 287 # Should replace the hash with the given keys taken away. 288 assert_equal expected, original.without!(:b, :c) 289 assert_equal expected, original 290 end 291 292 def test_indifferent_without 293 original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access 294 expected = { :c => 10 }.with_indifferent_access 295 296 [['a', 'b'], [:a, :b]].each do |keys| 297 # Should return a new hash without the given keys. 298 assert_equal expected, original.without(*keys), keys.inspect 299 assert_not_equal expected, original 300 301 # Should replace the hash without the given keys. 302 copy = original.dup 303 assert_equal expected, copy.without!(*keys) 304 assert_equal expected, copy 305 end 306 end 275 307 end 276 308 277 309 class IWriteMyOwnXML