class Syndi::Config

A class which provides a functional, simple configuration interface. It uses YAML by means of Psych.

@api Syndi @since 4.0.0 @author noxgirl @author swarley

@!attribute conf

@return [Hash{}] This is the hash which contains the data parsed from
  the configuration file.
@see #[]

Attributes

conf[R]
type[R]

Public Class Methods

new(filepath) click to toggle source

Produce a new instance, and attempt to parse.

@param [String] filepath Path to configuration file.

# File lib/syndi/config.rb, line 30
def initialize filepath
  $m.verbose("Trying to initialize configuration from '#{filepath}'...", VSIMPLE) do
    @path = filepath
    parse
  end # verbose
end

Public Instance Methods

[](key) click to toggle source

Return value of @conf.

@return [Object] Value of @conf. @see @conf

# File lib/syndi/config.rb, line 73
def [] key
  @conf[key]
end
rehash!() click to toggle source

Rehash the configuration.

If an error occurs, it will revert the configuration to its prior state so that everything can continue to function.

# File lib/syndi/config.rb, line 41
def rehash!
  
  $m.debug("Configuration file is rehashing.")

  # Keep the old configuration in case of issues.
  oldconf = @conf
  @conf   = {}

  # Rehash
  parse!

  # Ensure it really succeeded.
  if @conf.empty? or !@conf.instance_of? Hash
    # Nope. Restore old configuration.
    @conf = oldconf
    $m.error 'Failed to rehash the configuration file (parser produced empty config)! Reverting to old configuration.'
    return 0
  end
  
  $m.events.call :rehash

# This rescue is applicable to anything that happens in here, since if it is reached, there really was an error in general.
rescue => e 
  $m.error 'Failed to rehash configuration file! Reverting to old configuration.', false, e.backtrace
  @conf = oldconf
  return 0
end

Private Instance Methods

parse() click to toggle source

Parse the configuration file, and output the data to {#x}.

@raise [ConfigError] If the file does not exist. @raise [ConfigError] If the file cannot be processed.

# File lib/syndi/config.rb, line 85
def parse

  # Ensure foremost that the configuration file exists.
  unless File.exists? @path
    raise ConfigError, "Configuration file '#@path' does not exist!"
  end

  # Get the data from the file.
  f    = File.open(@path)
  data = f.read
  f.close

  conf = {}
  # Process the YAML.
  begin
    conf = Psych.load data
  rescue => e
    raise ConfigError, "Failed to process the YAML in '#@path'", e.backtrace
  end

  @conf = conf

end