Class: NxtInit::Option
- Inherits:
-
Object
- Object
- NxtInit::Option
- Defined in:
- lib/nxt_init/option.rb
Constant Summary collapse
- InvalidOptionError =
Class.new(ArgumentError)
Instance Attribute Summary collapse
-
#default_value ⇒ Object
readonly
Returns the value of attribute default_value.
-
#key ⇒ Object
readonly
Returns the value of attribute key.
Instance Method Summary collapse
- #default_value_is_block? ⇒ Boolean
- #default_value_is_preprocessor? ⇒ Boolean
- #default_value_was_given? ⇒ Boolean
-
#initialize(key, default_value: NotProvidedOption.new) ⇒ Option
constructor
A new instance of Option.
- #requires_value? ⇒ Boolean
- #resolve(attrs, target:) ⇒ Object
Constructor Details
#initialize(key, default_value: NotProvidedOption.new) ⇒ Option
Returns a new instance of Option.
5 6 7 8 |
# File 'lib/nxt_init/option.rb', line 5 def initialize(key, default_value: NotProvidedOption.new) @key = key @default_value = default_value end |
Instance Attribute Details
#default_value ⇒ Object (readonly)
Returns the value of attribute default_value.
10 11 12 |
# File 'lib/nxt_init/option.rb', line 10 def default_value @default_value end |
#key ⇒ Object (readonly)
Returns the value of attribute key.
10 11 12 |
# File 'lib/nxt_init/option.rb', line 10 def key @key end |
Instance Method Details
#default_value_is_block? ⇒ Boolean
38 39 40 |
# File 'lib/nxt_init/option.rb', line 38 def default_value_is_block? default_value && default_value.respond_to?(:call) end |
#default_value_is_preprocessor? ⇒ Boolean
42 43 44 |
# File 'lib/nxt_init/option.rb', line 42 def default_value_is_preprocessor? default_value_is_block? && default_value.arity == 1 end |
#default_value_was_given? ⇒ Boolean
46 47 48 |
# File 'lib/nxt_init/option.rb', line 46 def default_value_was_given? !default_value.is_a?(NotProvidedOption) end |
#requires_value? ⇒ Boolean
34 35 36 |
# File 'lib/nxt_init/option.rb', line 34 def requires_value? !default_value_was_given? end |
#resolve(attrs, target:) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/nxt_init/option.rb', line 12 def resolve(attrs, target:) if default_value_was_given? key_missing = !attrs.key?(key) given_value = attrs[key] if default_value_is_preprocessor? key_missing ? raise_key_error : target.instance_exec(given_value, &default_value) else # only when the given value was nil we will evaluate the fallback --> false is a valid value if given_value.nil? default_value_is_block? ? target.instance_exec(&default_value) : default_value else given_value end end elsif requires_value? attrs.fetch(key) { |_| raise_key_error } else raise InvalidOptionError, "Don't know how to deal with #{self}" end end |