class DaemonKit::Config

Simplify simple config file loading for daemons. Assumes the config files all live in DAEMON_ROOT/config and are YAML files. Loaded configs are accessed like a hash with string keys.

Config files can either be keyed by environment (default behavior) or be a normal hash.

Load a config by passing the filename (with or without the .yml extension) to load.

At this stage the configs are read-only.

Any of the keys can be called as methods as well.

Public Class Methods

hash( config, symbolize = false ) click to toggle source

Return the config.yml file as a raw hash.

# File lib/daemon_kit/config.rb, line 39
def hash( config, symbolize = false )
  self.load( config ).to_h( symbolize )
end
load( config ) click to toggle source

Load the config.yml file from DAEMON_ROOT/config

# File lib/daemon_kit/config.rb, line 25
def load( config )
  config = config.to_s
  config += '.yml' unless config =~ /\.yml$/

  path = File.join( DAEMON_ROOT, 'config', config )

  raise ArgumentError, "Can't find #{path}" unless File.exists?( path )

  config_content = ERB.new(File.read(path)).result(binding)

  new( YAML.load( config_content ) )
end

Public Instance Methods

[]( key ) click to toggle source

Pick out a config by name

# File lib/daemon_kit/config.rb, line 55
def []( key )
  @data[ key.to_s ]
end
data=( hash ) click to toggle source
# File lib/daemon_kit/config.rb, line 80
def data=( hash )
  @data = hash
  class << @data
    def symbolize_keys( hash = self )
      hash.inject({}) { |result, (key, value)|
        new_key = case key
                when String then key.to_sym
                else key
                end
        new_value = case value
                when Hash then symbolize_keys(value)
                else value
                end
        result[new_key] = new_value
        result
      }
    end
  end

  extend_hash( @data )
end
extend_hash( hash ) click to toggle source
# File lib/daemon_kit/config.rb, line 102
    def extend_hash( hash )
      hash.keys.each do |k|
        hash.instance_eval <<-KEY
          def #{k.gsub(/\-/, '_')}
            fetch("#{k}")
          end
        KEY
      end

      hash.each do |(key, value)|
        case value
          when Hash then extend_hash( value )
        end
      end
    end
to_h( symbolize = false ) click to toggle source

Return the internal hash structure used, optionally symbolizing the first level of keys in the hash

# File lib/daemon_kit/config.rb, line 61
def to_h( symbolize = false )
  symbolize ? @data.symbolize_keys : @data
end