Sha256: 6a594378c6624a5adddf0e3e3f0fb7cf23f4bf9b1990b2806737fc6c3fb40845
Contents?: true
Size: 972 Bytes
Versions: 5
Compression:
Stored size: 972 Bytes
Contents
require "ostruct" class Hash # Recursively converts a <tt>Hash</tt> and all nested <tt>Hash</tt>es to # <tt>OpenStruct</tt>s. Especially useful for parsing YAML. # # @example # 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" def to_ostruct arr = map { |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 } OpenStruct.new(Hash[arr]) end end
Version data entries
5 entries across 5 versions & 1 rubygems