Class: NotNaughty::LengthValidation

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

Overview

Validates length of obj’s attribute via the :length method.

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

Options:

:message

see NotNaughty::Errors for details

:if

see NotNaughty::Validation::Condition for details

:unless

see NotNaughty::Validation::Condition for details

Boundaries (by precendence):

:is

valid length

:within

valid range of length

:minimum

maximum length

:maximum

minimum length

If both, :minimum and :maximum are provided they’re converted to :within. Each boundary type has its own default message:

precise

“Length of %s is not equal to #__length.”

range

“Length of %s is not within #__range__range.first and #__range__range.last.”

lower

“Length of %s is smaller than #__boundary.”

upper

“Length of %s is greater than #__boundary.”

Example:

obj = %w[a sentence with five words] # 
def obj.errors() @errors ||= NotNauthy::Errors.new end

LengthValidation.new({:minimum => 4}, :to_a).
  call obj, :to_a, %w[a sentence with five words]
obj.errors.on(:to_s).any? # => false

LengthValidation.new({:within => 1..4}, :to_a).
  call obj, :to_a, %w[a sentence with five words]
obj.errors.on(:to_s).any? # => true

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) ⇒ LengthValidation

:nodoc:



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/not_naughty/validations/length_validation.rb', line 40

def initialize(opts, attributes) #:nodoc:
  
  block = build_block opts
  
  if opts[:allow_blank]
    super opts, attributes do |o, a, v|
      block[o, a, v] unless v.blank?
    end
  else
    super opts, attributes do |o, a, v|
      block[o, a, v] unless v.nil?
    end
  end
end