Class: WhyValidationsSuckIn96::ValidatesLength

Inherits:
Validation show all
Includes:
AttributeBasedValidation, SkippableValidation
Defined in:
lib/whyvalidationssuckin96/macros/validates_length.rb

Overview

Checks the validity of an attribute against a given set of sizes.

Examples:

Checking against an exact value

setup_validations do
  validates_length_of :choices, :is => 4
end

Checking against a range

setup_validations do
  validates_length_of :choices, :in => 1..10
end

Checking against a minimum value

setup_validations do
  validates_length_of :choices, :minimum => 1
end

Checking against a maximum value

setup_validations do
  validates_length_of :choices, :maximum => 10
end

Checking against a minimum and maximum value

setup_validations do
  validates_length_of :choices, :minimum => 1, :maximum => 10
end

Constant Summary collapse

DefaultOptions =
{:message => "does not meet the given length restrictions"}
ValidOptions =
[:is, :in, :minimum, :maximum]
OptionIncompatibility =
{
  :is => [:minimum, :maximum, :in],
  :in => [:minimum, :maximum, :is]
}

Instance Attribute Summary

Attributes inherited from Validation

#options, #validatable

Instance Method Summary collapse

Methods included from AttributeBasedValidation

#attribute, #attribute_value, #validates?

Methods inherited from Validation

#failed?, #has_run?, #message, new_subclass, #passed?, #validates?

Constructor Details

#initialize(validatable, options = {}) ⇒ ValidatesLength

Returns a new instance of ValidatesLength.

Parameters:

  • validatable (Object)

    An object to be validated.

  • options (Hash) (defaults to: {})

    The options to set up the validation with.

Options Hash (options):

  • :is (#==)

    An exact value to check the validatable object’s #size against.

  • :in (#include?)

    A range to check the validatable object’s #size against.

  • :minimum (#<=)

    A minimum value to check the validatable object’s size against.

  • :maximum (#>=)

    A maximum value to check the validatable object’s size against.



49
50
51
52
# File 'lib/whyvalidationssuckin96/macros/validates_length.rb', line 49

def initialize(validatable, options = {})
  super
  check_options(options)
end

Instance Method Details

#validateObject



54
55
56
57
58
59
60
61
62
# File 'lib/whyvalidationssuckin96/macros/validates_length.rb', line 54

def validate
  super
  fail unless attribute_value.respond_to?(:size)
  all_valid = ValidOptions.collect do |opt_name|
    next(true) if options[opt_name].nil?
    send(:"validate_#{opt_name}")
  end.all?
  all_valid ? pass : fail
end