Class: AmberbitConfig::HashStruct
- Inherits:
-
OpenStruct
- Object
- OpenStruct
- AmberbitConfig::HashStruct
- Defined in:
- lib/amberbit-config/hash_struct.rb
Overview
Main class that holds whole configuration, acts as open struct, with few tune ups
Class Method Summary collapse
-
.create(object) ⇒ Object
Creates a deeply nested HashStruct from hash.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Adds access to existing keys through hash operator.
-
#initialize(hash = nil) ⇒ HashStruct
constructor
Initialize with check for conflicts within hash keys.
-
#method_missing(method, *args, &block) ⇒ Object
Raise an error if method/configuration isn’t set yet.
-
#to_hash ⇒ Object
Generates a nested Hash object which is a copy of existing configuration.
Constructor Details
#initialize(hash = nil) ⇒ HashStruct
Initialize with check for conflicts within hash keys
7 8 9 10 |
# File 'lib/amberbit-config/hash_struct.rb', line 7 def initialize(hash = nil) check_hash_for_conflicts hash if hash super end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
Raise an error if method/configuration isn’t set yet. It should prevent typos, because normally it will just return a nil. With this check you can spot those earlier.
26 27 28 29 30 31 32 |
# File 'lib/amberbit-config/hash_struct.rb', line 26 def method_missing(method, *args, &block) if method =~ /=\z/ || self.respond_to?(method) super else raise ConfigNotSetError, "Configuration option: '#{method}' was not set" end end |
Class Method Details
.create(object) ⇒ Object
Creates a deeply nested HashStruct from hash.
35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/amberbit-config/hash_struct.rb', line 35 def self.create(object) case object when Array object.map { |item| create(item) } when Hash mapped = {} object.each { |key, value| mapped[key] = create(value) } HashStruct.new mapped else object end end |
Instance Method Details
#[](key) ⇒ Object
Adds access to existing keys through hash operator
13 14 15 |
# File 'lib/amberbit-config/hash_struct.rb', line 13 def [](key) self.send key unless key == nil end |
#to_hash ⇒ Object
Generates a nested Hash object which is a copy of existing configuration
18 19 20 21 22 |
# File 'lib/amberbit-config/hash_struct.rb', line 18 def to_hash _copy = {} @table.each { |key, value| _copy[key] = value.is_a?(HashStruct) ? value.to_hash : value } _copy end |