Class: Poncho::EachValidator

Inherits:
Validator show all
Defined in:
lib/poncho/validator.rb

Overview

EachValidator is a validator which iterates through the attributes given in the options hash invoking the validate_each method passing in the record, attribute and value.

All Poncho validations are built on top of this validator.

Instance Attribute Summary collapse

Attributes inherited from Validator

#options

Instance Method Summary collapse

Methods inherited from Validator

kind, #kind

Constructor Details

#initialize(options) ⇒ EachValidator

Returns a new validator instance. All options will be available via the options reader, however the :attributes option will be removed and instead be made available through the attributes reader.



127
128
129
130
131
132
# File 'lib/poncho/validator.rb', line 127

def initialize(options)
  @attributes = Array(options.delete(:attributes))
  raise ':attributes cannot be blank' if @attributes.empty?
  super
  check_validity!
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



122
123
124
# File 'lib/poncho/validator.rb', line 122

def attributes
  @attributes
end

Instance Method Details

#check_validity!Object

Hook method that gets called by the initializer allowing verification that the arguments supplied are valid. You could for example raise an ArgumentError when invalid options are supplied.



154
155
# File 'lib/poncho/validator.rb', line 154

def check_validity!
end

#validate(record) ⇒ Object

Performs validation on the supplied record. By default this will call validates_each to determine validity therefore subclasses should override validates_each with validation logic.



137
138
139
140
141
142
143
# File 'lib/poncho/validator.rb', line 137

def validate(record)
  attributes.each do |attribute|
    value = record.read_attribute_for_validation(attribute)
    next if (value.nil? && options[:allow_nil]) || (value == "" && options[:allow_blank])
    validate_each(record, attribute, value)
  end
end

#validate_each(record, attribute, value) ⇒ Object

Override this method in subclasses with the validation logic, adding errors to the records errors array where necessary.

Raises:

  • (NotImplementedError)


147
148
149
# File 'lib/poncho/validator.rb', line 147

def validate_each(record, attribute, value)
  raise NotImplementedError, 'Subclasses must implement a validate_each(record, attribute, value) method'
end