Module: YAMLCon

Defined in:
lib/yamlcon/version.rb,
lib/yamlcon/yamlcon.rb

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Class Method Details

.hash_to_struct(hash) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/yamlcon/yamlcon.rb', line 24

def self.hash_to_struct(hash)
  return hash unless hash.is_a? Hash
  dotted = OpenStruct.new hash

  hash.each do |key, value| 
    if value.is_a? Hash
      dotted[key] = hash_to_struct(value) 
    elsif value.is_a? Array
      dotted[key] = value.collect {|item| hash_to_struct item }
    end
  end

  dotted
end

.load_config(path) ⇒ Object



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

def self.load_config(path)
  if path.include? "*"
    result = OpenStruct.new
    Dir[path].each do |file|
      basename = File.basename(file).sub(/\..*/, '')
      result[basename] = hash_to_struct YAML.load_file(file)
    end
    result
  else
    hash_to_struct YAML.load_file(path)
  end
end

.save_config(file, data) ⇒ Object



18
19
20
21
22
# File 'lib/yamlcon/yamlcon.rb', line 18

def self.save_config(file, data)
  File.open file, 'w' do |f| 
    f.write struct_to_yaml data
  end
end

.struct_to_hash(dot_notation) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/yamlcon/yamlcon.rb', line 39

def self.struct_to_hash(dot_notation)
  return dot_notation unless dot_notation.is_a? OpenStruct

  hash = {}
  dot_notation.each_pair do |k, v| 
    if v.is_a? OpenStruct
      value = struct_to_hash(v) 
    elsif v.is_a? Array
      value = v.map { |val| struct_to_hash val }
    else
      value = v
    end

    hash[k.to_s] = value
  end
  hash
end

.struct_to_yaml(dot_notation) ⇒ Object



57
58
59
# File 'lib/yamlcon/yamlcon.rb', line 57

def self.struct_to_yaml(dot_notation)
  struct_to_hash(dot_notation).to_yaml
end