Class: YTools::YamlObject

Inherits:
Object
  • Object
show all
Defined in:
lib/ytools/yaml_object.rb,
lib/ytools/templates/yaml_object.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil, root = nil, ypath = nil) ⇒ YamlObject

Returns a new instance of YamlObject.



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ytools/yaml_object.rb', line 21

def initialize(hash=nil, root=nil, ypath=nil)
  if hash.nil?
    @yhash = {}
  else
    @yhash = hash.dup
  end

  @ypath = ypath || '/'
  @methods = {}
  @yroot = root || self

  merge(@yhash)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/ytools/yaml_object.rb', line 46

def method_missing(sym, *args, &block)
  method_name = sym.to_s
  hash_key = @methods[method_name]

  if hash_key.nil?
    raise YTools::PathError.new("unable to locate attribute: '#{relative_ypath}/#{method_name}'")
  else
    @yhash[hash_key]
  end
end

Instance Attribute Details

#yhashObject (readonly)

Returns the value of attribute yhash.



19
20
21
# File 'lib/ytools/yaml_object.rb', line 19

def yhash
  @yhash
end

#ypathObject (readonly)

Returns the value of attribute ypath.



19
20
21
# File 'lib/ytools/yaml_object.rb', line 19

def ypath
  @ypath
end

#yrootObject (readonly)

Returns the value of attribute yroot.



19
20
21
# File 'lib/ytools/yaml_object.rb', line 19

def yroot
  @yroot
end

Class Method Details

.from_files(files, strict = nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/ytools/yaml_object.rb', line 5

def self.from_files(files, strict=nil)
  yo = YTools::YamlObject.new
  files.each do |file|
    if File.exists?(file)
      contents = nil
      File.open(file, 'r') { |f| contents = f.read}
      yo.merge(YAML::load(contents))
    elsif strict
      raise YTools::PathError.new("non-existant YAML file: #{file}")
    end
  end
  yo
end

Instance Method Details

#[](key) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/ytools/yaml_object.rb', line 57

def [](key)
  value = @yhash[key]
  if value.nil?
    raise YTools::PathError.new("unable to locate key: \"#{relative_ypath}@['#{key}']\"")
  end
  value
end

#[]=(key, value) ⇒ Object



65
66
67
# File 'lib/ytools/yaml_object.rb', line 65

def []=(key, value)
  add_entry(key, value)
end

#erb_bindingObject

ERB bindings



7
8
9
# File 'lib/ytools/templates/yaml_object.rb', line 7

def erb_binding
  binding
end

#merge(hash) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/ytools/yaml_object.rb', line 35

def merge(hash) 
  return if hash.nil?
  if !hash.is_a?(Hash)
    raise YTools::PathError.new("malformed YAML:\n#{hash}")
  end

  hash.each do |key, value|
    add_entry(key, value)
  end
end

#to_sObject



69
70
71
# File 'lib/ytools/yaml_object.rb', line 69

def to_s
  @yhash.to_s
end