Class: Apiwork::Configuration
- Inherits:
-
Object
- Object
- Apiwork::Configuration
- Defined in:
- lib/apiwork/configuration.rb,
lib/apiwork/configuration/option.rb,
lib/apiwork/configuration/validatable.rb
Overview
Typed access to configuration values with automatic defaults.
Defined Under Namespace
Modules: Validatable Classes: Option
Instance Method Summary collapse
-
#dig(*keys) ⇒ Object
Accesses nested configuration values by key path.
-
#initialize(options_source, storage = {}) ⇒ Configuration
constructor
A new instance of Configuration.
- #merge(hash) ⇒ Object
- #method_missing(name, *args, &block) ⇒ Object
- #respond_to_missing?(name, include_private = false) ⇒ Boolean
-
#to_h ⇒ Hash
Converts the configuration to a hash.
Constructor Details
#initialize(options_source, storage = {}) ⇒ Configuration
Returns a new instance of Configuration.
17 18 19 20 |
# File 'lib/apiwork/configuration.rb', line 17 def initialize(, storage = {}) @options = () @storage = storage end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/apiwork/configuration.rb', line 22 def method_missing(name, *args, &block) option = @options[name] raise ConfigurationError, "Unknown option: #{name}" unless option if args.empty? && !block return @storage[name] = true if option.type == :boolean stored = @storage[name] if option.nested? nested_storage = stored || {} return Configuration.new(option, nested_storage) end return stored.nil? ? option.default : stored end value = args.first if block && option.nested? @storage[name] ||= {} nested = Configuration.new(option, @storage[name]) block.arity.positive? ? yield(nested) : nested.instance_eval(&block) else option.validate!(value) @storage[name] = value end end |
Instance Method Details
#dig(*keys) ⇒ Object
Accesses nested configuration values by key path.
67 68 69 |
# File 'lib/apiwork/configuration.rb', line 67 def dig(*keys) keys.compact.reduce(self) { |config, key| config.public_send(key) } end |
#merge(hash) ⇒ Object
54 55 56 |
# File 'lib/apiwork/configuration.rb', line 54 def merge(hash) Configuration.new(@options, @storage.deep_merge(hash)) end |
#respond_to_missing?(name, include_private = false) ⇒ Boolean
50 51 52 |
# File 'lib/apiwork/configuration.rb', line 50 def respond_to_missing?(name, include_private = false) @options.key?(name) || super end |
#to_h ⇒ Hash
Converts the configuration to a hash.
78 79 80 81 82 83 84 85 86 87 |
# File 'lib/apiwork/configuration.rb', line 78 def to_h @options.each_with_object({}) do |(name, option), result| if option.nested? result[name] = Configuration.new(option, @storage[name] || {}).to_h else stored = @storage[name] result[name] = stored.nil? ? option.default : stored end end end |