Class: AdsCommon::Config

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

Instance Method Summary collapse

Constructor Details

#initialize(param = nil) ⇒ Config

Initialized the Config object with either the contents of a provided file or a provided hash.



33
34
35
36
37
38
39
# File 'lib/ads_common/config.rb', line 33

def initialize(param = nil)
  @config = {}
  case param
    when String then load(param)
    when Hash then set_all(param)
  end
end

Instance Method Details

#load(filename) ⇒ Object

Reads a configuration file into instance variable as a Ruby structure with the complete set of keys and values.

Args:

  • filename: config file to be read (String)

Raises:

  • Errno::ENOENT if the file does not exist.



82
83
84
85
86
87
88
89
90
91
# File 'lib/ads_common/config.rb', line 82

def load(filename)
  new_config = YAML::load_file(filename)
  if new_config.kind_of?(Hash)
    @config = new_config
  else
    raise AdsCommon::Errors::Error,
        "Incorrect configuration file: %s" % filename
  end
  return nil
end

#read(property_path, default_value = nil) ⇒ Object

Reads a property or category from the loaded configuration. They can be indexed using a dot-based notation (e.g. “category.property” to access “property” under “category”).

Returns the specified default if no value found.



46
47
48
49
# File 'lib/ads_common/config.rb', line 46

def read(property_path, default_value = nil)
  result = find_value(@config, property_path)
  return (result.nil?) ? default_value : result
end

#set(property_path, value) ⇒ Object

Writes a new value to a property or category in memory (creating it if necessary). They can be indexed using a dot-based notation (e.g. “category.property” to access “property” under “category”).



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/ads_common/config.rb', line 55

def set(property_path, value)
  if property_path
    last_node = @config
    last_name = property_path.split('.').inject(nil) do |last_name, section|
      last_node = last_node[last_name] ||= {} unless last_name.nil?
      section.to_sym
    end
    last_node[last_name] = value
  end
  return nil
end

#set_all(properties) ⇒ Object

Writes an entire set of properties.



68
69
70
71
# File 'lib/ads_common/config.rb', line 68

def set_all(properties)
  @config = process_hash_keys(properties)
  return nil
end