Class: ControllerValidator::Validator

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/controller_validator/validator.rb

Overview

Nearly entirely lifted from the example code in the Rails Documentation. See: www.rubydoc.info/docs/rails/ActiveModel/Errors

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Validator

Returns a new instance of Validator.



11
12
13
# File 'lib/controller_validator/validator.rb', line 11

def initialize(*args)
  @errors = ::ActiveModel::Errors.new(self)
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



9
10
11
# File 'lib/controller_validator/validator.rb', line 9

def errors
  @errors
end

Class Method Details

.human_attribute_name(attr, options = {}) ⇒ Object



33
34
35
# File 'lib/controller_validator/validator.rb', line 33

def self.human_attribute_name(attr, options = {})
  attr.to_s.humanize
end

.lookup_ancestorsObject



37
38
39
# File 'lib/controller_validator/validator.rb', line 37

def self.lookup_ancestors
  [self]
end

Instance Method Details

#read_attribute_for_validation(attr) ⇒ Object

The following methods are needed to be minimally implemented



29
30
31
# File 'lib/controller_validator/validator.rb', line 29

def read_attribute_for_validation(attr)
  send(attr)
end

#validateObject

Raises:

  • (RuntimeError)


23
24
25
# File 'lib/controller_validator/validator.rb', line 23

def validate
  raise RuntimeError, 'Must be defined in subclass of ControllerValidator'
end

#validate_and_push_errors_to(instance:) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/controller_validator/validator.rb', line 15

def validate_and_push_errors_to(instance:)
  unless self.validate!
    self.errors.full_messages.each do |message|
      instance.errors.add(:base, message)
    end
  end
end