Sha256: ee93cc9d66d1b32921f2436f32b22894fdcfef9b01275d797da8a2e54b183b4e

Contents?: true

Size: 1.78 KB

Versions: 3

Compression:

Stored size: 1.78 KB

Contents

#!/usr/bin/env ruby

class Object
  def symbolize; self; end
end

class String
    def symbolize; match(/\A\w+\z/) ? to_sym : self; end
end

class Array
  def symbolize; map { |e| e.symbolize }; end
end

class Hash
  def symbolize
    inject({}) do |hash, (attribute, value)|
      hash[attribute.symbolize] = value.symbolize
      hash
    end
  end
end

if __FILE__ == $0
  require 'test/unit'
  
  class TestSymbolize < Test::Unit::TestCase
    def test_integer_symbolize
      assert_equal(1, 1.symbolize)
    end
    
    def test_string_symbolize
      assert_equal(:expected, "expected".symbolize)
    end
    
    def test_array_symbolize
      array = ('a'..'d').to_a
      expected = array.map { |e| e.to_sym }
      
      assert_equal(expected, array.symbolize)
    end
    
    def test_hash_symbolize
      hash = {'a' => 'x', 'b' => 'y', 'c' => 'z'}
      
      expected = hash.inject({}) { |h, (a, v)|  h[a.to_sym] = v.to_sym; h }
      
      assert_equal(expected, hash.symbolize)
    end

    def test_array_with_non_word_element
      assert_equal([:a, :b, :c, 'x x'], ['a', 'b', 'c', 'x x'].symbolize)
    end

    def test_hash_with_non_word_strings
      assert_equal( {:a => :x, :b => :y, :c => 'a b', 'x x' => :c},
                    { 'a' => 'x', 
                      'b' => 'y', 
                      'c' => 'a b', 
                      'x x' => 'c'
                    }.symbolize 
                  )
    end

    def test_hash_with_array_inside
      assert_equal( {:a => :x, :b => [ :c, :d, 'x x']},
                    {'a' => 'x', 'b' => [ 'c', 'd', 'x x']}.symbolize )
    end
    
    def test_array_with_hash_inside                             
      assert_equal( [:a , { :b => :c, :d => 'x x'}],
                    ['a' , { 'b' => 'c', 'd' => 'x x'}].symbolize )
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tartan-0.2.0 lib/core_ext/symbolize.rb
tartan-0.1.1 lib/symbolize.rb
tartan-0.2.1 lib/core_ext/symbolize.rb