Class: Konfa::Base

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

Class Method Summary collapse

Class Method Details

.after_initializeObject



111
112
# File 'lib/konfa.rb', line 111

def after_initialize
end

.allowed_variablesObject



45
46
47
# File 'lib/konfa.rb', line 45

def allowed_variables
  {}
end

.dumpObject



74
75
76
# File 'lib/konfa.rb', line 74

def dump
  self.configuration.dup
end

.env_variable_prefixObject

The following methods should be overridden and used to configure the configuration class



41
42
43
# File 'lib/konfa.rb', line 41

def env_variable_prefix
  'APP_'
end

.false?(variable) ⇒ Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/konfa.rb', line 66

def false?(variable)
  self.true?(variable) == false
end

.get(variable) ⇒ Object

The following methods provides the interface to this class



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

def get(variable)
  raise UnsupportedVariableError.new(variable) unless self.configuration.has_key? variable
  self.configuration[variable]
end

.initialize_from_envObject



97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/konfa.rb', line 97

def initialize_from_env
  conf_prefix = self.env_variable_prefix.upcase

  ENV.keys.reject { |key|
    key !~ /^#{conf_prefix}/ # Ignore everything that doesn't match the prefix
  }.each { |key|
    variable = key[conf_prefix.size..-1].downcase

    self.store(variable, ENV[key])
  }
  after_initialize
  dump
end

.initialize_from_yaml(path) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/konfa.rb', line 78

def initialize_from_yaml(path)
  # FIXME: It would be a lot cleaner if the YAML library would raise an
  # exception if it fails to read the file. We'll handle it like this for now
  # load_file just returns "false" if it fails

  yaml_data = YAML.load_file(path)

  unless yaml_data.nil?
    raise InitializationError.new("Bad YAML format, key/value pairs expected") unless yaml_data.kind_of?(Hash)

    yaml_data.each do |variable, value|
      self.store(variable, value)
    end
  end

  after_initialize
  dump
end

.on_key_missing(key, value) ⇒ Object



49
50
51
# File 'lib/konfa.rb', line 49

def on_key_missing(key, value)
  raise UnsupportedVariableError.new(key)
end

.true?(variable) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/konfa.rb', line 62

def true?(variable)
  self.truthy?(self.get(variable))
end

.variablesObject



70
71
72
# File 'lib/konfa.rb', line 70

def variables
  self.configuration.keys
end

.with_config(overrides = {}) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/konfa.rb', line 114

def with_config(overrides={})
  original_config = dump
  overrides.each_pair {|k,v| self.store(k, v) }

  begin
    result = yield
  ensure
    self.configuration = original_config
  end

  result
end