Class: Capistrano::Configuration::ValidatedVariables
- Inherits:
-
SimpleDelegator
- Object
- SimpleDelegator
- Capistrano::Configuration::ValidatedVariables
- Includes:
- ProcHelpers
- Defined in:
- lib/capistrano/configuration/validated_variables.rb
Overview
Decorates a Variables object to additionally perform an optional set of user-supplied validation rules. Each rule for a given key is invoked immediately whenever ‘set` is called with a value for that key.
If ‘set` is called with a callable value or a block, validation is not performed immediately. Instead, the validation rules are invoked the first time `fetch` is used to access the value.
A rule is simply a block that accepts two arguments: key and value. It is up to the rule to raise an exception when it deems the value is invalid (or just print a warning).
Rules can be registered using the DSL like this:
validate(:my_key) do |key, value|
# rule goes here
end
Defined Under Namespace
Classes: ValidatedQuestion
Instance Method Summary collapse
-
#initialize(variables) ⇒ ValidatedVariables
constructor
A new instance of ValidatedVariables.
-
#set(key, value = nil, &block) ⇒ Object
Decorate Variables#set to add validation behavior.
-
#validate(key, &validator) ⇒ Object
Register a validation rule for the given key.
Methods included from ProcHelpers
Constructor Details
#initialize(variables) ⇒ ValidatedVariables
Returns a new instance of ValidatedVariables.
27 28 29 30 |
# File 'lib/capistrano/configuration/validated_variables.rb', line 27 def initialize(variables) super(variables) @validators = {} end |
Instance Method Details
#set(key, value = nil, &block) ⇒ Object
Decorate Variables#set to add validation behavior.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/capistrano/configuration/validated_variables.rb', line 33 def set(key, value=nil, &block) assert_value_or_block_not_both(value, block) # Skip validation behavior if no validators are registered for this key return super unless validators.key?(key) value_to_evaluate = block || value if callable_without_parameters?(value_to_evaluate) super(key, assert_valid_later(key, value_to_evaluate), &nil) else assert_valid_now(key, value_to_evaluate) super end end |
#validate(key, &validator) ⇒ Object
Register a validation rule for the given key.
50 51 52 53 54 |
# File 'lib/capistrano/configuration/validated_variables.rb', line 50 def validate(key, &validator) vs = (validators[key] || []) vs << validator validators[key] = vs end |