Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/toolshed/hash.rb

Direct Known Subclasses

Toolshed::Client

Instance Method Summary collapse

Instance Method Details

#to_ostruct ⇒ Object

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/toolshed/hash.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