Sha256: 94eb47756fafa37165aa1654cf815903e3edd08de0c400376ac910ba09131de8

Contents?: true

Size: 1.86 KB

Versions: 11

Compression:

Stored size: 1.86 KB

Contents

module DaemonKit

  # 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.
  class Config

    class << self

      # Load the +config+.yml file from DAEMON_ROOT/config
      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 )

        new( YAML.load_file( path ) )
      end

      # Return the +config+.yml file as a raw hash.
      def hash( config, symbolize = false )
        self.load( config ).to_h( symbolize )
      end

    end

    # Expects a hash, looks for DAEMON_ENV key
    def initialize( config_data ) #:nodoc:
      if config_data.has_key?( DAEMON_ENV )
        @data = config_data[ DAEMON_ENV ]
      else
        @data = config_data
      end
    end

    # Pick out a config by name
    def []( key )
      @data[ key.to_s ]
    end

    # Return the internal hash structure used, optionally symbolizing
    # the first level of keys in the hash
    def to_h( symbolize = false )
      symbolize ? @data.inject({}) { |m,c| m[c[0].to_sym] = c[1]; m } : @data
    end

    def method_missing( method_name, *args ) #:nodoc:
      # don't match setters
      unless method_name.to_s =~ /[\w_]+=$/
        # pick a key if we have it
        return @data[ method_name.to_s ] if @data.keys.include?( method_name.to_s )
      end

      super
    end
  end
end

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
kennethkalmer-daemon-kit-0.1.7.3 lib/daemon_kit/config.rb
kennethkalmer-daemon-kit-0.1.7.4 lib/daemon_kit/config.rb
kennethkalmer-daemon-kit-0.1.7.5 lib/daemon_kit/config.rb
kennethkalmer-daemon-kit-0.1.7.7 lib/daemon_kit/config.rb
kennethkalmer-daemon-kit-0.1.7.8 lib/daemon_kit/config.rb
kennethkalmer-daemon-kit-0.1.7.9 lib/daemon_kit/config.rb
daemon-kit-0.1.7.7 lib/daemon_kit/config.rb
daemon-kit-0.1.7.8 lib/daemon_kit/config.rb
daemon-kit-0.1.7.9 lib/daemon_kit/config.rb
daemon-kit-0.1.7.4 lib/daemon_kit/config.rb
daemon-kit-0.1.7.5 lib/daemon_kit/config.rb