Class: AppConf
- Inherits:
-
Object
show all
- Defined in:
- lib/app_conf.rb
Instance Method Summary
collapse
Constructor Details
Returns a new instance of AppConf.
7
8
9
|
# File 'lib/app_conf.rb', line 7
def initialize
@hash = {}
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
58
59
60
61
62
63
64
|
# File 'lib/app_conf.rb', line 58
def method_missing(method, *args, &block)
if method[-1] == '='
self[method[0..-2]] = args.first
else
self[method]
end
end
|
Instance Method Details
#[](key) ⇒ Object
49
50
51
|
# File 'lib/app_conf.rb', line 49
def [](key)
value = @hash[key.to_s]
end
|
#[]=(key, value) ⇒ Object
53
54
55
56
|
# File 'lib/app_conf.rb', line 53
def []=(key, value)
raise "Not allowed to overwrite nested entities" if @hash[key.to_s].is_a?(AppConf)
@hash[key.to_s] = value
end
|
#clear(key = nil) ⇒ Object
34
35
36
37
|
# File 'lib/app_conf.rb', line 34
def clear key = nil
key ? @hash[key.to_s] = nil : @hash = {}
nil
end
|
#from_hash(hash) ⇒ Object
66
67
68
69
70
71
72
|
# File 'lib/app_conf.rb', line 66
def from_hash(hash)
hash.each do |key, value|
value = (self[key] || AppConf.new).from_hash(value) if value.is_a?(Hash)
@hash[key.to_s] = value
end
self
end
|
#keys ⇒ Object
45
46
47
|
# File 'lib/app_conf.rb', line 45
def keys
@hash.keys
end
|
#load(*filenames) ⇒ Object
11
12
13
14
15
16
|
# File 'lib/app_conf.rb', line 11
def load(*filenames)
filenames.each do |filename|
content = YAML.load_file(filename)
from_hash(content) if content
end
end
|
#save(key, filename) ⇒ Object
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
# File 'lib/app_conf.rb', line 18
def save(key, filename)
mode = File.exist?(filename) ? 'r+' : 'w+'
File.open(filename, mode) do |f|
unless f.eof?
begin
pos = f.pos
line = f.readline
end until line =~ /^---/ || f.eof?
line =~ /^---/ ? f.seek(pos) : f.rewind
end
hash = {key.to_s => self[key].to_hash}
YAML.dump(hash, f)
f.truncate(f.pos)
end
end
|
#to_hash ⇒ Object
39
40
41
42
43
|
# File 'lib/app_conf.rb', line 39
def to_hash
hash = {}
@hash.each {|k, v| hash[k] = v.is_a?(AppConf) ? v.to_hash : v }
hash
end
|