Method: Hash#to_ostruct

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

- (Object) to_ostruct

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| el.respond_to?(:to_ostruct) ? el.to_ostruct : el }]
    else
      [k, v]
    end
  end
  OpenStruct.new(Hash[arr])
end

Comments