Class: Quiver::Validator
- Inherits:
-
Object
- Object
- Quiver::Validator
- Defined in:
- lib/quiver/validator.rb
Constant Summary collapse
- VALIDATORS =
{ presence: Quiver::Validators::Presence, unique: Quiver::Validators::Unique }.freeze
Instance Method Summary collapse
-
#initialize(definitions) ⇒ Validator
constructor
A new instance of Validator.
- #validate(object, options = {}) ⇒ Object
Constructor Details
#initialize(definitions) ⇒ Validator
Returns a new instance of Validator.
14 15 16 |
# File 'lib/quiver/validator.rb', line 14 def initialize(definitions) self.definitions = definitions end |
Instance Method Details
#validate(object, options = {}) ⇒ Object
18 19 20 21 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/quiver/validator.rb', line 18 def validate(object, ={}) = [:tags] || [] error_collections = definitions.map do |definition| next unless (, definition) if definition[:options][:if] next if !definition[:options][:if].call(object) end if definition[:options][:unless] next if definition[:options][:unless].call(object) end attr_or_proc = definition[:attr_or_proc] = definition[:options].select do |k, v| !%i|except only if unless|.include?(k) end if attr_or_proc.is_a?(Proc) result = attr_or_proc.call(object) unless result.is_a?(Quiver::ErrorCollection) raise TypeError, 'proc validators must return a Quiver::ErrorCollection' end result else value = object.public_send(attr_or_proc) results = .map do |k, v| validator_klass = VALIDATORS[k] || next validator = validator_klass.new( value, v, attr_or_proc, [:mapper], [:model] ) validator.validate end results.compact.reduce(:+) end end error_collections.compact.reduce(:+) || Quiver::ErrorCollection.new end |