Class: Fhcap::JsonConfig

Inherits:
FHConfig show all
Defined in:
lib/fhcap/misc/json_config.rb

Instance Attribute Summary

Attributes inherited from FHConfig

#config, #file, #node

Instance Method Summary collapse

Methods inherited from FHConfig

#add, #attribute_file_content, #from_attributes_file, #has_upper_recipe_override, #is_json?, #parse_key, #parse_value, #to_chef_attributes

Constructor Details

#initializeJsonConfig

Returns a new instance of JsonConfig.



8
9
10
# File 'lib/fhcap/misc/json_config.rb', line 8

def initialize
  super
end

Instance Method Details

#from_file(filename, force = false, overrides = []) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/fhcap/misc/json_config.rb', line 12

def from_file(filename, force=false, overrides=[])
  if File.exists?(filename) && File.readable?(filename)
    json = JSON.parse(IO.read(filename))
    from_json(json, force, overrides)
  else
    raise IOError, "Cannot open or read #{filename}!"
  end
end

#from_json(json, force = false, overrides = []) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/fhcap/misc/json_config.rb', line 21

def from_json(json, force=false, overrides=[])
  keys = get_keys(json)
  keys.each do |tuple|
    current = tuple[0]
    value = tuple[1]
    add(current, value, force, overrides)
  end
end

#get_keys(s, c = nil, keys = nil) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/fhcap/misc/json_config.rb', line 30

def get_keys(s, c=nil, keys=nil)
  if s.is_a? String
    s = JSON.parse(s)
  end
  keys ||= []
  c ||= []
  s.each_pair do |key, value|
    c.push(key)
    if value.class == Hash
      get_keys(value, c, keys)
      if value == {}
        keys.push([c.clone, parse_value(value.to_json)])
      end
    elsif value.class == Array
      #  value.each_with_index do |val, ind|
      #    c.push(ind.to_s)
      #    get_keys(val, c, keys)
      #    c.pop
      #  end
      keys.push([c.clone, JSON.parse(value.to_json)])
    else
      keys.push([c.clone, parse_value(value.to_json)])
    end
    c.pop
  end
  keys
end