Class: DaemonKit::Config
- Inherits:
-
Object
- Object
- DaemonKit::Config
- Defined in:
- lib/daemon_kit/config.rb
Overview
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 Method Summary collapse
-
.load(config) ⇒ Object
Load the
config
.yml file from DAEMON_ROOT/config.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Pick out a config by name.
-
#initialize(config_data) ⇒ Config
constructor
Expects a hash, looks for DAEMON_ENV key.
-
#method_missing(method_name, *args) ⇒ Object
:nodoc:.
-
#to_h(symbolize = false) ⇒ Object
Return the internal hash structure used, optionally symbolizing the first level of keys in the hash.
Constructor Details
#initialize(config_data) ⇒ Config
Expects a hash, looks for DAEMON_ENV key
35 36 37 38 39 40 41 |
# File 'lib/daemon_kit/config.rb', line 35 def initialize( config_data ) #:nodoc: if config_data.has_key?( DAEMON_ENV ) @data = config_data[ DAEMON_ENV ] else @data = config_data end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args) ⇒ Object
:nodoc:
54 55 56 57 58 59 60 61 62 |
# File 'lib/daemon_kit/config.rb', line 54 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 |
Class Method Details
.load(config) ⇒ Object
Load the config
.yml file from DAEMON_ROOT/config
22 23 24 25 26 27 28 29 30 |
# File 'lib/daemon_kit/config.rb', line 22 def load( config ) 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 |
Instance Method Details
#[](key) ⇒ Object
Pick out a config by name
44 45 46 |
# File 'lib/daemon_kit/config.rb', line 44 def []( key ) @data[ key.to_s ] end |
#to_h(symbolize = false) ⇒ Object
Return the internal hash structure used, optionally symbolizing the first level of keys in the hash
50 51 52 |
# File 'lib/daemon_kit/config.rb', line 50 def to_h( symbolize = false ) symbolize ? @data.inject({}) { |m,c| m[c[0].to_sym] = c[1]; m } : @data end |