Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

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  
    1111      #   end 
    1212      # 
    1313      #   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)) 
    1419      module Slice 
    1520        # Returns a new hash with only the given keys. 
    1621        def slice(*keys) 
     
    2227        def slice!(*keys) 
    2328          replace(slice(*keys)) 
    2429        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 
    2541      end 
    2642    end 
    2743  end 
  • activesupport/test/core_ext/hash_ext_test.rb

    old new  
    272272      assert_equal expected, copy 
    273273    end 
    274274  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 
    275307end 
    276308 
    277309class IWriteMyOwnXML