Class: HaveAPI::ValidatorChain
- Inherits:
-
Object
- Object
- HaveAPI::ValidatorChain
- Defined in:
- lib/haveapi/validator_chain.rb
Overview
A chain of validators for one input parameter.
Instance Method Summary collapse
-
#add_or_replace(name, opt) ⇒ Object
Adds validator that takes option
namewith configuration inopt. - #describe ⇒ Object
-
#initialize(args) ⇒ ValidatorChain
constructor
A new instance of ValidatorChain.
-
#required? ⇒ Boolean
Returns true if validator Validators::Presence is used.
-
#validate(value, params) ⇒ Object
Validate
valueusing all configured validators.
Constructor Details
#initialize(args) ⇒ ValidatorChain
Returns a new instance of ValidatorChain.
4 5 6 7 8 9 10 11 12 13 14 15 |
# File 'lib/haveapi/validator_chain.rb', line 4 def initialize(args) @validators = [] @required = false find_validators(args) do |validator| obj = validator.use(args) next unless obj.useful? @required = true if obj.is_a?(Validators::Presence) @validators << obj end end |
Instance Method Details
#add_or_replace(name, opt) ⇒ Object
Adds validator that takes option name with configuration in opt. If such validator already exists, it is reconfigured with newly provided opt.
If opt is nil, the validator is removed.
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 49 |
# File 'lib/haveapi/validator_chain.rb', line 22 def add_or_replace(name, opt) args = { name => opt } unless (v_class = find_validator(args)) raise "validator for '#{name}' not found" end exists = @validators.detect { |v| v.is_a?(v_class) } obj = exists if exists if opt.nil? @validators.delete(exists) else exists.reconfigure(name, opt) @validators.delete(exists) unless exists.useful? end else obj = v_class.use(args) @validators << obj if obj.useful? end return unless v_class == Validators::Presence @required = !opt.nil? && obj.useful? end |
#describe ⇒ Object
56 57 58 59 60 61 62 63 |
# File 'lib/haveapi/validator_chain.rb', line 56 def describe ret = {} @validators.each do |v| ret[v.class.name] = v.describe end ret end |
#required? ⇒ Boolean
Returns true if validator Validators::Presence is used.
52 53 54 |
# File 'lib/haveapi/validator_chain.rb', line 52 def required? @required end |
#validate(value, params) ⇒ Object
Validate value using all configured validators. It returns either true if the value passed all validators or an array of errors.
68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/haveapi/validator_chain.rb', line 68 def validate(value, params) ret = [] @validators.each do |validator| next if validator.validate(value, params) ret << format(validator., value:) end ret.empty? ? true : ret end |