sgosh
sgosh

Reputation: 27

How to get children from YAML nodes in ERB

I am using ERB to access the contents of a YAML file. How can I directly include the childs and subchilds of nodes in ERB from a YAML-file structured like this:

Parent:
  Child1: ABC
  Child2:
    Subchild1: 123
    Subchild2: 456
  Child3: XYZ

Using <%= Parent.Child2.Subchild1 %> does not work. Is this possible at all or can this only be achieved with a loop?

Upvotes: 0

Views: 816

Answers (2)

David Lilue
David Lilue

Reputation: 631

What you want require to dynamically create classes or instances. This can be difficult to understand at the beginning but maybe this can help you.

require 'yaml'

def parser_yaml_as_class input
    input.each do |k,v|
        if v.class == Hash
            parser_yaml_as_class v
            new_class = Class.new do
                v.each do |sub_key,sub_value|
                    self.class_eval("def self.#{sub_key.to_sym};@#{sub_key.to_sym};end")
                    self.class_eval("def self.#{sub_key.to_sym}=(val);@#{sub_key.to_sym}=val;end")

                    if sub_value.class == Hash
                        self.send "#{sub_key.to_sym}=".to_sym, Object.const_get(sub_key)
                    else
                        self.send "#{sub_key.to_sym}=".to_sym, sub_value
                    end
                end
            end
            Object.const_set(k,new_class)
        end
    end
end

parser_yaml_as_class(YAML.load_file('in.yml'))

puts Parent.Child1
#=> "ABC"
puts Parent.Child2
#=> Child2 # Child2 class
puts Parent.Child2.Subchild1
#=> 123

Upvotes: 0

Ursus
Ursus

Reputation: 30071

You get the file as an hash. Example

thing = YAML.load_file('some.yml')
puts thing["Child2"]["Subchild1"] # 123

Upvotes: 1

Related Questions