Class: ConfigHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/config_handler.rb

Constant Summary collapse

CONFIG_DIRECTORY =
".vdms.d"
CONFIG_FILENAME =
"config"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.config_parameter(name) ⇒ Object



69
70
71
72
73
74
# File 'lib/config_handler.rb', line 69

def self.config_parameter(name)
  instance = ConfigHandler.new
  instance.load_config_values
  result = @@config_values[name]
  result = result ? result : ""
end

Instance Method Details

#delete(name) ⇒ Object



90
91
92
# File 'lib/config_handler.rb', line 90

def delete(name)
  set(name, nil)
end

#file_contents(filename) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/config_handler.rb', line 40

def file_contents(filename)
  if (File.file? filename)
    File.open(filename, "r")
  else
    []
  end
end

#get(name) ⇒ Object



76
77
78
79
# File 'lib/config_handler.rb', line 76

def get(name)
  load_config_values
  @@config_values[name]
end

#get_config_file ⇒ Object



5
6
7
8
9
10
# File 'lib/config_handler.rb', line 5

def get_config_file
  if (! File.directory?(CONFIG_DIRECTORY))
    FileUtils.mkdir(CONFIG_DIRECTORY)
  end
  CONFIG_DIRECTORY + File::SEPARATOR + CONFIG_FILENAME
end

#load_config_values ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/config_handler.rb', line 48

def load_config_values
  if defined? @@config_values
    return
  else
    @@config_values = {}
    if (! File.file?(get_config_file))
      return
    end
    File.open(get_config_file).each { |line|
      line = line.strip
      if line[0] == '#'
        continue
      end
      name, value = parse_line(line)
      if value
        @@config_values[name] = value
      end
    }
  end
end

#parse_line(line) ⇒ Object



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

def parse_line(line)
  idx = line.index('=')
  if (idx)
    return line[0...idx], line[idx+1..-1]
  else
    line
  end
end

#replace_nv(name, value, new_file, old_file_contents) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/config_handler.rb', line 21

def replace_nv(name, value, new_file, old_file_contents)
  new_config_line = name + '=' + value
  wrote_line = false
  old_file_contents.each { |line|
    old_name, old_value = parse_line(line)
    if (old_name == name)
      if ! value.nil?
        new_file.puts(new_config_line)
      end
      wrote_line = true
    else
      new_file.puts(line)
    end
  }
  if ( ! wrote_line)
    new_file.puts(new_config_line)
  end
end

#set(name, value) ⇒ Object



81
82
83
84
85
86
87
88
# File 'lib/config_handler.rb', line 81

def set(name, value)
  config_file = get_config_file
  new_config_file = config_file + ".tmp"
  updated_file = File.open(new_config_file, "w")
  replace_nv(name, value, updated_file, file_contents(config_file))
  updated_file.close
  FileUtils.mv(new_config_file, config_file, :force => true)
end