class AdsCommon::Config
Public Class Methods
Initialized the Config
object with either the contents of a provided file or a provided hash.
# File lib/ads_common/config.rb, line 30 def initialize(param = nil) @config = {} case param when String then load(param) when Hash then set_all(param) end end
Public Instance Methods
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.
# File lib/ads_common/config.rb, line 79 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' (%s)" % [filename, e] end return nil end
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.
# File lib/ads_common/config.rb, line 43 def read(property_path, default_value = nil) result = find_value(@config, property_path) return (result.nil?) ? default_value : result end
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”).
# File lib/ads_common/config.rb, line 52 def set(property_path, value) if property_path last_node = @config last_name = property_path.split('.').inject(nil) do |name, section| last_node = last_node[name] ||= {} unless name.nil? section.to_sym end last_node[last_name] = value end return nil end
Writes an entire set of properties.
# File lib/ads_common/config.rb, line 65 def set_all(properties) @config = process_hash_keys(properties) return nil end
Private Instance Methods
Finds a value for string of format 'level1.level2.name' in a given hash.
# File lib/ads_common/config.rb, line 109 def find_value(data, path) return (path.nil? or data.nil?) ? nil : path.split('.').inject(data) do |node, section| break if node.nil? key = section.to_sym (node.is_a?(Hash) and node.include?(key)) ? node[key] : nil end end
Auxiliary method to recurse through a hash and convert all the keys to symbols.
# File lib/ads_common/config.rb, line 99 def process_hash_keys(hash) return hash.inject({}) do |result, pair| key, value = pair result[key.to_sym] = value.is_a?(Hash) ? process_hash_keys(value) : value result end end