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

Ticket #7369: hash-without.2.diff

File hash-without.2.diff, 2.7 kB (added by mpalmer, 1 year ago)

Rebased patch

  • 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  
    290290    assert_equal expected, original.except!(:c) 
    291291    assert_equal expected, original 
    292292  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 
    293325end 
    294326 
    295327class IWriteMyOwnXML