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

I’m sorry for using eval here…

Constant Summary collapse

TEMPLATE =
<<-BLOCK
proc do |obj, attr, value|
  value.%s or %s value.length or
  obj.errors.add attr, %s
end
BLOCK

Constants inherited from Validation

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, load_paths, new

Constructor Details

#initialize(valid, attributes) ⇒ LengthValidation

:nodoc:



49
50
51
# File 'lib/not_naughty/validations/length_validation.rb', line 49

def initialize(valid, attributes) #:nodoc:
  super valid, attributes, &build_block(valid)
end