Class: Rbdantic::Validators::Types::Model
- Defined in:
- lib/rbdantic/validators/types/model.rb
Overview
Validator for nested model types
Instance Attribute Summary collapse
-
#model_class ⇒ Object
readonly
Returns the value of attribute model_class.
Attributes inherited from Base
Instance Method Summary collapse
- #expected_type_name ⇒ Object
-
#initialize(model_class, **constraints) ⇒ Model
constructor
A new instance of Model.
- #matches_type?(value) ⇒ Boolean
-
#validate(value, location = [], strict: false) ⇒ Object
Model validation has special handling for nil and Hash so we override validate entirely.
- #validate_constraints(value, _errors, _location, strict: false) ⇒ Object
Methods inherited from Base
Constructor Details
#initialize(model_class, **constraints) ⇒ Model
Returns a new instance of Model.
12 13 14 15 |
# File 'lib/rbdantic/validators/types/model.rb', line 12 def initialize(model_class, **constraints) super(**constraints) @model_class = model_class end |
Instance Attribute Details
#model_class ⇒ Object (readonly)
Returns the value of attribute model_class.
10 11 12 |
# File 'lib/rbdantic/validators/types/model.rb', line 10 def model_class @model_class end |
Instance Method Details
#expected_type_name ⇒ Object
21 22 23 |
# File 'lib/rbdantic/validators/types/model.rb', line 21 def expected_type_name @model_class.name end |
#matches_type?(value) ⇒ Boolean
17 18 19 |
# File 'lib/rbdantic/validators/types/model.rb', line 17 def matches_type?(value) value.is_a?(@model_class) end |
#validate(value, location = [], strict: false) ⇒ Object
Model validation has special handling for nil and Hash so we override validate entirely
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 |
# File 'lib/rbdantic/validators/types/model.rb', line 27 def validate(value, location = [], strict: false) return [[], nil] if value.nil? if matches_type?(value) return [validate_existing_instance(value, location, strict: strict), value] end if value.is_a?(::Hash) if strict return [ [error(type: :type_error, loc: location, msg: "Expected #{expected_type_name}, got Hash", input: value)], value ] end begin return [[], @model_class.new(value)] rescue ValidationError => e return [remap_errors(e.errors, location), value] end end [ [error(type: :type_error, loc: location, msg: "Expected #{expected_type_name}, got #{value.class.name}", input: value)], value ] end |
#validate_constraints(value, _errors, _location, strict: false) ⇒ Object
54 55 56 |
# File 'lib/rbdantic/validators/types/model.rb', line 54 def validate_constraints(value, _errors, _location, strict: false) value end |