Class: Konfigyu::Config

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

Overview

Does the meat of the work

Constant Summary collapse

DEFAULT_FILENAME =
'konfigyu.yml'.freeze
DEFAULT_EXAMPLE_FILENAME =
'konfigyu.yml.example'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config_file = nil, options = {}) ⇒ Config

Options Example:

options =

required_fields: [
  'top_level', 'top_level.second_level_field',
  'log', 'log.level',
],
required_values: {
  'log.level': %w{none fatal error warn info debug,
}

}



24
25
26
27
28
29
30
31
32
33
# File 'lib/konfigyu/config.rb', line 24

def initialize(config_file = nil, options = {})
  self.config_file = config_file.nil? ? File.expand_path("~/#{DEFAULT_FILENAME}") : File.expand_path(config_file)
  if !self.config_file || !File.exist?(self.config_file)
    raise Konfigyu::FileNotFoundException, "Missing configuration file: #{self.config_file}"
  end

  self.data = Sycl.load_file(self.config_file)
  @options = initialize_options(options)
  validate
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/konfigyu/config.rb', line 49

def method_missing(method_name, *args, &block)
  return super unless data

  config_chain = method_name.to_s
  if !config_chain.chomp!('=').nil?
    data[config_chain] = args.first
  elsif deep_key_exists?(config_chain)
    data[config_chain]
  else
    super
  end
end

Instance Attribute Details

#config_fileObject

Returns the value of attribute config_file.



7
8
9
# File 'lib/konfigyu/config.rb', line 7

def config_file
  @config_file
end

#dataObject

Returns the value of attribute data.



7
8
9
# File 'lib/konfigyu/config.rb', line 7

def data
  @data
end

#optionsObject

Returns the value of attribute options.



7
8
9
# File 'lib/konfigyu/config.rb', line 7

def options
  @options
end

Instance Method Details

#[](key) ⇒ Object



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

def [](key)
  data.get(key)
end

#respond_to_missing?(method_name, _include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


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

def respond_to_missing?(method_name, _include_private = false)
  data && !deep_key_exists?(method_name.to_s.chomp('=')).nil?
end

#validateObject



35
36
37
38
39
# File 'lib/konfigyu/config.rb', line 35

def validate
  validate_usage
  validate_required_fields
  validate_required_values
end