Class: RCLConf::RCLConf

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

Constant Summary collapse

KEYWORDS =
{
	''			=>	nil, 
	'nil'		=>	nil,
	'false'	=>	false,
	'true'	=>	true,
}

Instance Method Summary collapse

Constructor Details

#initialize(argv, defaults = {}) ⇒ RCLConf

Returns a new instance of RCLConf.



14
15
16
17
18
19
# File 'lib/rclconf/rclconf.rb', line 14

def initialize(argv, defaults={})
	@argv = parse_argv(argv)
	@defaults = defaults
	@loaded = {}
    @runtime = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rclconf/rclconf.rb', line 34

def method_missing(method, *args)
	key = method.to_s
    if(match = /(.*)=$/.match(key))
      @runtime.store(match[1], args.first)
    else
      @runtime.fetch(key) {
        @argv.fetch(key) {
          @loaded.fetch(key) { 
            @defaults.fetch(key) { super }
          }
        }
      }
    end
end

Instance Method Details

#load(files, opts = {:trusted => false}) ⇒ Object



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

def load(files, opts = {:trusted => false})
  if(files.class == Array)
    files.each { |file|
      if(File.exist?(file) && File.readable?(file))
        self.load(file, opts)
        break
      end
    }
  else
    src = File.read(files)
    src.untaint if(opts[:trusted])
    @loaded = YAML.load(src)
  end
end

#parse_argv(data) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/rclconf/rclconf.rb', line 48

def parse_argv(data)
	data.inject({}) { |memo, line| 
		key, val = line.split("=", 2)
		val = KEYWORDS.fetch(val, val)
		memo.store(key, val)
		memo
	}
end

#reset!Object



56
57
58
# File 'lib/rclconf/rclconf.rb', line 56

def reset!
  @runtime.clear
end

#respond_to?(symbol) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
62
63
# File 'lib/rclconf/rclconf.rb', line 59

def respond_to?(symbol)
    key = symbol.to_s
    /=$/.match(key) || [@runtime, @argv, @loaded, @defaults].any? { |coll|
      coll.include?(key) }
end