Class: Libis::Tools::ConfigFile

Inherits:
DeepStruct show all
Defined in:
lib/libis/tools/config_file.rb

Overview

The ConfigFile class is a convenience class for interfacing with YAML configuration files. These files can contain ERB statements. An initial hash or file can be loaded during initialization. The class supports loading and saving of files, but note that any ERB statements in the file are lost by performing such a round trip. The class is derived from the DeepStruct class and therefore supports nested hashes and arrays and supports the OpenStruct style of accessors.

The parameters can be accessed by getter/setter method or using the Hash syntax:

require 'libis/tools/config_file'
cfg_file = ::Libis::Tools::ConfigFile.new
cfg_file << {foo: 'bar'}
cfg_file.my_value = 10
p cfg_file[:my_value] # => 10
cfg_file{:my_text] = 'abc'
p cfg_file['my_text'] # => 'abc'
p cfg_file.to_hash # => { :foo => 'bar', 'my_value' => 10, :my_text => 'abc' }
cfg >> 'my_config.yml'

Instance Method Summary collapse

Methods inherited from DeepStruct

#clear!, #each, #key?, #keys, #merge, #merge!

Constructor Details

#initialize(file_or_hash = nil, opt = {}) ⇒ ConfigFile

Create a new ConfigFile instance. The optional argument can either be a Hash or a String. The argument is passed to the #<< method after initialization.

Parameters:

  • file_or_hash (String, Hash) (defaults to: nil)

    optional String or Hash argument to initialize the data.



35
36
37
# File 'lib/libis/tools/config_file.rb', line 35

def initialize(file_or_hash = nil, opt = {})
  super _file_to_hash(file_or_hash), opt
end

Instance Method Details

#<<(file_or_hash, &block) ⇒ Object

Load configuration parameters from a YAML file or Hash.

The YAML file can contain ERB syntax values that will be evaluated at loading time. Instead of a YAML file, a Hash can be passed.

Note that the method also yields the hash or absolute path to a given block. This is for data management of derived classes such as ::Libis::Tools::Config.

Parameters:

  • file_or_hash (String, Hash)

    optional String or Hash argument to initialize the data.



48
49
50
# File 'lib/libis/tools/config_file.rb', line 48

def <<(file_or_hash, &block)
  self.merge!(_file_to_hash(file_or_hash, &block))
end

#>>(file) ⇒ Object

Save configuration parameters in a YAML file.

Parameters:

  • file (String)

    path of the YAML file to save the configuration to.



55
56
57
# File 'lib/libis/tools/config_file.rb', line 55

def >>(file)
  File.open(file, 'w') { |f| f.write to_hash.to_yaml }
end