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.



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

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.



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

def load(filename)
  begin
    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
  rescue TypeError => e
    raise AdsCommon::Errors::Error,
        "Error parsing 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.



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

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”).



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

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.



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

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