Class: Rbdantic::Validators::ModelValidator
- Inherits:
-
Object
- Object
- Rbdantic::Validators::ModelValidator
- Defined in:
- lib/rbdantic/validators/model_validator.rb
Overview
Decorator for model-level validators Usage:
model_validator mode: :before do |data|
data[:email] = data[:email]&.downcase
data
end
Constant Summary collapse
- MODES =
i[before after].freeze
Instance Attribute Summary collapse
-
#mode ⇒ Object
readonly
Returns the value of attribute mode.
-
#validator_proc ⇒ Object
readonly
Returns the value of attribute validator_proc.
Instance Method Summary collapse
-
#call(data) ⇒ Hash
Execute the :before validator, which receives and must return a Hash.
-
#initialize(mode: :after, &block) ⇒ ModelValidator
constructor
A new instance of ModelValidator.
-
#validate(model_instance) ⇒ Array<ErrorDetail>
Run validation and collect errors.
Constructor Details
#initialize(mode: :after, &block) ⇒ ModelValidator
Returns a new instance of ModelValidator.
16 17 18 19 |
# File 'lib/rbdantic/validators/model_validator.rb', line 16 def initialize(mode: :after, &block) @mode = validate_mode!(mode) @validator_proc = block end |
Instance Attribute Details
#mode ⇒ Object (readonly)
Returns the value of attribute mode.
14 15 16 |
# File 'lib/rbdantic/validators/model_validator.rb', line 14 def mode @mode end |
#validator_proc ⇒ Object (readonly)
Returns the value of attribute validator_proc.
14 15 16 |
# File 'lib/rbdantic/validators/model_validator.rb', line 14 def validator_proc @validator_proc end |
Instance Method Details
#call(data) ⇒ Hash
Execute the :before validator, which receives and must return a Hash. Only valid to call when mode == :before.
25 26 27 |
# File 'lib/rbdantic/validators/model_validator.rb', line 25 def call(data) @validator_proc.call(data) end |
#validate(model_instance) ⇒ Array<ErrorDetail>
Run validation and collect errors
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/rbdantic/validators/model_validator.rb', line 32 def validate(model_instance) errors = [] begin @validator_proc.call(model_instance) rescue StandardError => e errors << ErrorDetail.new( type: :model_validation_failed, loc: [], msg: e., input: nil ) end errors end |