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

Ticket #591: stringify_keys.diff

File stringify_keys.diff, 2.0 kB (added by Ulysses, 4 years ago)

Patch adding Hash#stringify_keys and Hash#stringify_keys!

  • test/core_ext/hash_ext_test.rb

    old new  
    1515    assert_respond_to h, :symbolize_keys! 
    1616    assert_respond_to h, :to_options 
    1717    assert_respond_to h, :to_options! 
     18    assert_respond_to h, :stringify_keys 
     19    assert_respond_to h, :stringify_keys! 
    1820  end 
    1921 
    2022  def test_symbolize_keys 
     
    3335    assert_raises(NoMethodError) { { [] => 1 }.symbolize_keys! } 
    3436  end 
    3537 
     38  def test_stringify_keys 
     39    assert_equal @strings, @strings.stringify_keys 
     40    assert_equal @strings, @symbols.stringify_keys 
     41    assert_equal @strings, @mixed.stringify_keys 
     42 
     43    assert_raises(NoMethodError) { { [] => 1 }.symbolize_keys } 
     44  end 
     45 
     46  def test_stringify_keys! 
     47    assert_equal @strings, @strings.dup.stringify_keys! 
     48    assert_equal @strings, @symbols.dup.stringify_keys! 
     49    assert_equal @strings, @mixed.dup.stringify_keys! 
     50 
     51    assert_raises(NoMethodError) { { [] => 1 }.symbolize_keys! } 
     52  end 
     53 
     54 
    3655  def test_assert_valid_keys 
    3756    assert_nothing_raised do 
    3857      { :failure => "stuff", :funny => "business" }.assert_valid_keys([ :failure, :funny ]) 
  • lib/core_ext/hash/keys.rb

    old new  
    2121          end 
    2222          self 
    2323        end 
     24         
     25        # Return a new hash with all keys converted to strings. 
     26        def stringify_keys 
     27          inject({}) {|options, (key, value)| options[key.to_s] = value; options} 
     28        end 
     29        # Destructively convert all keys to strings. 
     30        def stringify_keys! 
     31          keys.each do |key| 
     32            unless key.kind_of?(String) 
     33              self[key.to_s] = self[key] 
     34              delete key 
     35            end 
     36          end 
     37          self 
     38        end 
    2439 
    2540        alias_method :to_options,  :symbolize_keys 
    2641        alias_method :to_options!, :symbolize_keys!