Class: Philiprehberger::ConfigValidator::Rule
- Inherits:
-
Object
- Object
- Philiprehberger::ConfigValidator::Rule
- Defined in:
- lib/philiprehberger/config_validator/rule.rb
Overview
Represents a single validation rule for a configuration key
Instance Attribute Summary collapse
-
#allowed_values ⇒ Array?
readonly
Allowed values.
-
#default ⇒ Object?
readonly
The default value.
-
#key ⇒ Symbol
readonly
The configuration key.
-
#required ⇒ Boolean
readonly
Whether the key is required.
-
#type ⇒ Class
readonly
The expected type.
Instance Method Summary collapse
-
#apply_default(config) ⇒ void
Apply default value to config if key is missing.
-
#initialize(key, type, required:, default: nil, one_of: nil) ⇒ Rule
constructor
A new instance of Rule.
-
#validate(config) ⇒ Array<String>
Validate a configuration hash against this rule.
Constructor Details
#initialize(key, type, required:, default: nil, one_of: nil) ⇒ Rule
Returns a new instance of Rule.
27 28 29 30 31 32 33 |
# File 'lib/philiprehberger/config_validator/rule.rb', line 27 def initialize(key, type, required:, default: nil, one_of: nil) @key = key @type = type @required = required @default = default @allowed_values = one_of end |
Instance Attribute Details
#allowed_values ⇒ Array? (readonly)
Returns allowed values.
20 21 22 |
# File 'lib/philiprehberger/config_validator/rule.rb', line 20 def allowed_values @allowed_values end |
#default ⇒ Object? (readonly)
Returns the default value.
17 18 19 |
# File 'lib/philiprehberger/config_validator/rule.rb', line 17 def default @default end |
#key ⇒ Symbol (readonly)
Returns the configuration key.
8 9 10 |
# File 'lib/philiprehberger/config_validator/rule.rb', line 8 def key @key end |
#required ⇒ Boolean (readonly)
Returns whether the key is required.
14 15 16 |
# File 'lib/philiprehberger/config_validator/rule.rb', line 14 def required @required end |
#type ⇒ Class (readonly)
Returns the expected type.
11 12 13 |
# File 'lib/philiprehberger/config_validator/rule.rb', line 11 def type @type end |
Instance Method Details
#apply_default(config) ⇒ void
This method returns an undefined value.
Apply default value to config if key is missing
58 59 60 61 62 63 |
# File 'lib/philiprehberger/config_validator/rule.rb', line 58 def apply_default(config) return if config.key?(key) || config.key?(key.to_s) return if default.nil? config[key] = default end |
#validate(config) ⇒ Array<String>
Validate a configuration hash against this rule
39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/philiprehberger/config_validator/rule.rb', line 39 def validate(config) errors = [] value = resolve_value(config) if value.nil? errors << "missing required key '#{key}'" if required return errors end validate_type(value, errors) validate_allowed(value, errors) errors end |