Class: NotNaughty::FormatValidation

Inherits:
Validation show all
Defined in:
lib/not_naughty/validations/format_validation.rb

Overview

Validates format of obj’s attribute via the :match method.

Unless the validation succeeds an error hash (:attribute => :message) is added to the obj’s instance of Errors.

Options:

:with

object that that’ll check via a :match call

:message

see NotNaughty::Errors for details

:if

see NotNaughty::Validation::Condition for details

:unless

see NotNaughty::Validation::Condition for details

Example:

obj = 'abc'
def obj.errors() @errors ||= NotNauthy::Errors.new end

FormatValidation.new({:with => /[a-z]/}, :to_s).call obj, :to_s, 'abc'
obj.errors.on(:to_s).any? # => false

FormatValidation.new({:with => /[A-Z]/}, :to_s).call obj, :to_s, 'abc'
obj.errors.on(:to_s) # => ["Format of to_s does not match."]

Direct Known Subclasses

NumericalityValidation

Constant Summary

Constants inherited from Validation

Validation::BASEDIR, Validation::PATTERN

Instance Attribute Summary

Attributes inherited from Validation

#attributes

Instance Method Summary collapse

Methods inherited from Validation

#call_with_conditions, #call_without_conditions, inherited, load, new

Constructor Details

#initialize(opts, attributes) ⇒ FormatValidation

:nodoc:



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/not_naughty/validations/format_validation.rb', line 26

def initialize(opts, attributes) #:nodoc:
  (__format = opts[:with]).respond_to? :match or
  raise ArgumentError, "#{__format.inspect} doesn't respond to :match"
  
  __message = opts[:message] || 'Format of %s does not match.'
  
  if opts[:allow_blank] or opts[:allow_nil]
    __allow = if opts[:allow_blank] then :blank? else :nil? end
    super opts, attributes do |o, a, v|
      o.errors.add a, __message unless v.send! __allow or __format.match v
    end
  else
    super opts, attributes do |o, a, v|
      o.errors.add a, __message unless __format.match v
    end
  end
end