Ticket #7369: hash-without.2.diff
| File hash-without.2.diff, 2.7 kB (added by mpalmer, 1 year 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 290 290 assert_equal expected, original.except!(:c) 291 291 assert_equal expected, original 292 292 end 293 294 def test_without 295 original = { :a => 'x', :b => 'y', :c => 10 } 296 expected = { :a => 'x' } 297 298 # Should return a hash without the given keys. 299 assert_equal expected, original.without(:b, :c) 300 assert_not_equal expected, original 301 302 # Should ignore non-existant keys. 303 assert_equal expected, original.without(:b, :c, :d) 304 305 # Should replace the hash with the given keys taken away. 306 assert_equal expected, original.without!(:b, :c) 307 assert_equal expected, original 308 end 309 310 def test_indifferent_without 311 original = { :a => 'x', :b => 'y', :c => 10 }.with_indifferent_access 312 expected = { :c => 10 }.with_indifferent_access 313 314 [['a', 'b'], [:a, :b]].each do |keys| 315 # Should return a new hash without the given keys. 316 assert_equal expected, original.without(*keys), keys.inspect 317 assert_not_equal expected, original 318 319 # Should replace the hash without the given keys. 320 copy = original.dup 321 assert_equal expected, copy.without!(*keys) 322 assert_equal expected, copy 323 end 324 end 293 325 end 294 326 295 327 class IWriteMyOwnXML