Sha256: fdf603b7da7e0ae28f3f18158b972070456a6b3ff7928ee2d151b7deb4c16755

Contents?: true

Size: 801 Bytes

Versions: 11

Compression:

Stored size: 801 Bytes

Contents

require 'ostruct'

class Hash

  # Like to_ostruct but recusively objectifies all hash elements as well.
  #
  #   o = { 'a' => { 'b' => 1 } }.to_ostruct_recurse
  #   o.a.b  #=> 1
  #
  def to_ostruct_recurse
    o = self.dup
    each_pair do |k,v|
      o[k] = v.to_ostruct_recurse if v.respond_to?( :to_ostruct_recurse )
    end
    ::OpenStruct.new( o )
  end

end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCHash < Test::Unit::TestCase

    def test_to_ostruct_recurse
      a = { :a => 1, :b => 2, :c => { :x => 4 } }
      ao = a.to_ostruct_recurse
      assert_equal(  a[:a], ao.a )
      assert_equal(  a[:b], ao.b )
      assert_equal(  a[:c][:x], ao.c.x )
    end

  end

=end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
facets-1.0.3 packages/core/lib/facet/hash/to_ostruct_recurse.rb
facets-0.9.0 lib/nano/hash/to_ostruct_recurse.rb
facets-1.0.0 lib/facet/hash/to_ostruct_recurse.rb
facets-1.3.0 lib/facets/core/hash/to_ostruct_recurse.rb
facets-1.1.0 lib/facet/hash/to_ostruct_recurse.rb
facets-1.2.0 lib/facets/core/hash/to_ostruct_recurse.rb
facets-1.2.1 lib/facets/core/hash/to_ostruct_recurse.rb
facets-1.3.3 lib/facets/core/hash/to_ostruct_recurse.rb
facets-1.3.1 lib/facets/core/hash/to_ostruct_recurse.rb
facets-1.3.2 lib/facets/core/hash/to_ostruct_recurse.rb
facets-1.4.0 lib/facets/core/hash/to_ostruct_recurse.rb