Method: Hash#to_ostruct

Defined in:
lib/shenanigans/hash/to_ostruct.rb

#to_ostructObject

Recursively converts a Hash and all nested Hashes to OpenStructs. Especially useful for parsing YAML.

yaml=<<EOY
subject: Programming Languages
languages:
  - name        : Ruby
    creator     : Matz
  - name        : Python
    creator     : Guido van Rossum
  - name        : Perl
    creator     : Larry Wall
EOY
struct = YAML.load(yaml).to_ostruct
struct.subject
#=> "Programming Languages"
struct.languages.first
#=> #<OpenStruct name="Ruby", creator="Matz">
struct.languages.first.creator
#=> "Matz"


23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/shenanigans/hash/to_ostruct.rb', line 23

def to_ostruct
  arr = map do |k, v|
    case v
    when Hash
      [k, v.to_ostruct]
    when Array
      [k, v.map { |el| Hash === el ? el.to_ostruct : el }]
    else
      [k, v]
    end
  end
  OpenStruct.new(arr)
end