Class: Vapir::Configuration::Option
- Inherits:
-
Object
- Object
- Vapir::Configuration::Option
- Defined in:
- lib/vapir-common/config.rb
Overview
represents a valid option on a Configuration. consists of a key and criteria for which a value is valid for that key.
Instance Attribute Summary collapse
-
#key ⇒ Object
readonly
Returns the value of attribute key.
-
#validator ⇒ Object
readonly
Returns the value of attribute validator.
Instance Method Summary collapse
-
#initialize(key, options = {}) ⇒ Option
constructor
creates a new option.
-
#validate!(value) ⇒ Object
takes a value and checks that it is valid, if a validator is specified for this option.
Constructor Details
#initialize(key, options = {}) ⇒ Option
creates a new option. the options hash (last argument) may specify a :validator key which will be used to validate any values attempted to be assigned to the key this option represents.
17 18 19 20 21 |
# File 'lib/vapir-common/config.rb', line 17 def initialize(key, ={}) @key = key = (, {}, [:validator]) @validator = [:validator] end |
Instance Attribute Details
#key ⇒ Object (readonly)
Returns the value of attribute key.
13 14 15 |
# File 'lib/vapir-common/config.rb', line 13 def key @key end |
#validator ⇒ Object (readonly)
Returns the value of attribute validator.
13 14 15 |
# File 'lib/vapir-common/config.rb', line 13 def validator @validator end |
Instance Method Details
#validate!(value) ⇒ Object
takes a value and checks that it is valid, if a validator is specified for this option. the validator may map the value to something different, so the result of this function call should replace the value being used.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/vapir-common/config.rb', line 25 def validate!(value) case @validator when nil value when Proc @validator.call value when :boolean case value when 'true', true true when 'false', false false else raise InvalidValueError, "value should look like a boolean for key #{key}; instead got #{value.inspect}" end when :numeric case value when Numeric value when String begin Float(value) rescue ArgumentError raise InvalidValueError, "value should look like a number for key #{key}; instead got #{value.inspect}" end else raise InvalidValueError, "value should look like a number for key #{key}; instead got #{value.inspect}" end when :positive_integer if value.is_a?(Integer) && value > 0 value elsif value.is_a?(String) && value.strip =~ /\A\d+\z/ && value.to_i > 0 value.to_i else raise InvalidValueError, "value should be a positive integer; got #{value.inspect}" end else raise ArgumentError, "invalid validator given: #{@validator.inspect}\nvalidator should be nil for unspecified, a Proc, or a symbol indicating a known validator type" end end |