Class: App::Config

Inherits:
Object
  • Object
show all
Includes:
DL::LoggerMixin
Defined in:
lib/app-ctx.rb

Overview

the priority of configuation settings is:

1. command line options
2. configuration from custom file, eg.: --config=/tmp/foo.yml
3. built-in default values from yaml file next to $0 script

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from DL::LoggerMixin

#debug, #error, #fatal, #info, #log_level, #logger, #set_log_level, #warn

Constructor Details

#initialize(params = {}) ⇒ Config

params are :argv and :defaults_path which are defaulting to ARGV and the applications defaults which are loaded from a yaml file next to the ‘$0’ application script.



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/app-ctx.rb', line 25

def initialize params = {}
    params = {
        :argv           => ARGV, 
        :defaults_path  => App.config_path($0)
    }.update(params)

    @argv = params[:argv]
    @defaults_path = params[:defaults_path] 
    
    load_config_file(@defaults_path)
    @values, @argv = parse_command_line @argv
end

Instance Attribute Details

#argvObject (readonly)

Returns the value of attribute argv.



20
21
22
# File 'lib/app-ctx.rb', line 20

def argv
  @argv
end

#defaults_pathObject (readonly)

Returns the value of attribute defaults_path.



20
21
22
# File 'lib/app-ctx.rb', line 20

def defaults_path
  @defaults_path
end

#valuesObject (readonly)

Returns the value of attribute values.



20
21
22
# File 'lib/app-ctx.rb', line 20

def values
  @values
end

Instance Method Details

#forward(target) ⇒ Object

continue processing of command line with next argument from cmdline



45
46
47
48
49
50
51
# File 'lib/app-ctx.rb', line 45

def forward(target)
    begin
        (op = argv.shift) && target.send(op, self)
    rescue ArgumentError => e
        target.send(op)
    end
end

#load_config_file(cpath) ⇒ Object

overwrite current configuration with values from file



64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/app-ctx.rb', line 64

def load_config_file cpath
    @values ||= {}
    if File.exists? cpath = File.expand_path(cpath)
        begin
            @values.update YAML.load_file(cpath)
            info "loaded(#{cpath})"
            debug "config values: #{@values.inspect}"
        rescue => e
            warn "failed to load: #{cpath}", e
        end
    else
        debug "no such config file: #{cpath}"
    end
end

#set_default_values(defaults) ⇒ Object

programatic way to define the default values other then from defaults file.



40
41
42
# File 'lib/app-ctx.rb', line 40

def set_default_values defaults
    @values = defaults.merge(@values)
end

#to_sObject



53
54
55
56
57
58
59
60
# File 'lib/app-ctx.rb', line 53

def to_s
 <<-EOT
args : #{argv.inspect}
      values : #{values.inspect}
    defaults : '#{defaults_path}'
 user config : '#{values[:config]}'
    EOT
end