Class: Rutty::Config
- Inherits:
-
Object
- Object
- Rutty::Config
- Defined in:
- lib/rutty/config.rb
Overview
Flexible config class able to use both hash accessors and object accessors. Nested attributes are also instances of this class, allowing for object (dot) style accessor chaining.
Direct Known Subclasses
Class Method Summary collapse
-
.load_config(dir) ⇒ Rutty::Config
Loads the default config data from the yaml file in the specified config dir.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Retrieve the specified key via Hash accessor syntax.
-
#[]=(key, value) ⇒ void
Set the specified key as the specified value via Hash accessor syntax.
-
#initialize(data = {}) ⇒ Config
constructor
Returns a new Config populated with the specified data hash.
-
#method_missing(sym, *args) ⇒ void
Allows for object accessor (dot) syntax to access the stored data.
-
#to_hash ⇒ Hash
Simply returns this instance’s @data attribute, which is internally stored as a hash.
-
#update!(data) ⇒ void
Updates this instance’s @data attribute with the specified data hash.
Constructor Details
#initialize(data = {}) ⇒ Config
Returns a new Rutty::Config populated with the specified data hash.
40 41 42 43 |
# File 'lib/rutty/config.rb', line 40 def initialize(data={}) @data = {} update!(data) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(sym, *args) ⇒ void
92 93 94 95 96 97 98 |
# File 'lib/rutty/config.rb', line 92 def method_missing(sym, *args) if sym.to_s =~ /(.+)=$/ self[$1] = args.first else self[sym] end end |
Class Method Details
.load_config(dir) ⇒ Rutty::Config
Loads the default config data from the yaml file in the specified config dir.
27 28 29 30 31 32 |
# File 'lib/rutty/config.rb', line 27 def load_config dir require 'yaml' data = YAML.load(File.open(File.join(dir, Rutty::Consts::GENERAL_CONF_FILE)).read) Rutty::Config.new data end |
Instance Method Details
#[](key) ⇒ Object
Retrieve the specified key via Hash accessor syntax.
61 62 63 |
# File 'lib/rutty/config.rb', line 61 def [](key) @data[key.to_sym] end |
#[]=(key, value) ⇒ void
Set the specified key as the specified value via Hash accessor syntax.
70 71 72 73 74 75 76 |
# File 'lib/rutty/config.rb', line 70 def []=(key, value) if value.class == Hash @data[key.to_sym] = Config.new(value) else @data[key.to_sym] = value end end |
#to_hash ⇒ Hash
Simply returns this instance’s @data attribute, which is internally stored as a hash.
82 83 84 |
# File 'lib/rutty/config.rb', line 82 def to_hash @data end |
#update!(data) ⇒ void
Updates this instance’s @data attribute with the specified data hash.
50 51 52 53 54 |
# File 'lib/rutty/config.rb', line 50 def update!(data) data.each do |key, value| self[key] = value end end |