Module: TypedModel::ModelValidations
- Defined in:
- lib/typed_model/model_validations.rb
Overview
Supplies a simple Errors facility with common validations
Implementations that mix in this module are expected to plug in validations
by overriding the validate method and/or adding before_validation hooks.
Calling valid? will return true or false and leave errors accessible
via errors which returns a Map<String,Array> of messages keyed by attribute.
Instance Attribute Summary collapse
-
#errors ⇒ Object
readonly
Returns the value of attribute errors.
Class Method Summary collapse
Instance Method Summary collapse
- #add_error(key, msg) ⇒ Object
- #assert_not_blank(field) ⇒ Object
- #assert_timestamp(field) ⇒ Object
- #each_error(&blk) ⇒ Object
- #valid? ⇒ Boolean
Instance Attribute Details
#errors ⇒ Object (readonly)
Returns the value of attribute errors.
16 17 18 |
# File 'lib/typed_model/model_validations.rb', line 16 def errors @errors end |
Class Method Details
.included(base) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/typed_model/model_validations.rb', line 18 def self.included(base) super base.class_eval do class << self def before_validation(fname) (@before_validation_callbacks ||= []) << fname end def before_validation_callbacks ancestors.reverse.each_with_object([]) do |c, callbacks| callbacks.concat(c.instance_variable_get(:@before_validation_callbacks) || []) end end end end end |
Instance Method Details
#add_error(key, msg) ⇒ Object
35 36 37 |
# File 'lib/typed_model/model_validations.rb', line 35 def add_error(key, msg) errors.add(key, msg) end |
#assert_not_blank(field) ⇒ Object
39 40 41 42 |
# File 'lib/typed_model/model_validations.rb', line 39 def assert_not_blank(field) v = send(field) add_error(field, :required) unless v.to_s.match?(/\S/) end |
#assert_timestamp(field) ⇒ Object
44 45 46 47 48 49 50 51 52 |
# File 'lib/typed_model/model_validations.rb', line 44 def (field) v = send(field) unless v.is_a?(Time) s = v.to_s send(:"#{field}=", Time.parse(s)) if s.match?(/\S/) end rescue StandardError add_error(field, :invalid) end |
#each_error(&blk) ⇒ Object
67 68 69 |
# File 'lib/typed_model/model_validations.rb', line 67 def each_error(&blk) errors.each_error(&blk) end |