Class: WhyValidationsSuckIn96::ValidatesExclusion

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

Overview

Checks the validity of an attribute against a collection of excluded values.

Examples:

Default usage

setup_validations do
  validates_exclusion_of :subdomain, :in => %w[www ftp]
end

Usage when checking a set of values against another set

setup_validations do
  validates_exclusion_of :colours, :in => %w[red green], :set => true
  # colours can now be an array containing anything except 'red' or 'green'
end

Constant Summary collapse

DefaultOptions =
{:message => "is in the excluded collection",
:set     => false}

Instance Attribute Summary

Attributes inherited from Validation

#options, #validatable

Instance Method Summary collapse

Methods included from AttributeBasedValidation

#attribute, #validates?

Methods inherited from Validation

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

Constructor Details

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

Returns a new instance of ValidatesExclusion.

Parameters:

  • validatable (Object)

    An object to be validated.

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

    The options to set up the validation with.

Options Hash (options):

  • :in (#include?)

    A collection to check against for exclusion.

  • :set (true, false)

    Whether or not to do a set based comparison

Raises:

  • (ArgumentError)


29
30
31
32
# File 'lib/whyvalidationssuckin96/macros/validates_exclusion.rb', line 29

def initialize(validatable, options = {})
  super
  raise(ArgumentError, "Collection to check for exclusion against should be specified with :in") unless options[:in]
end

Instance Method Details

#validateObject



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/whyvalidationssuckin96/macros/validates_exclusion.rb', line 34

def validate
  super
  if options[:set]
    attribute_value.any? do |val|
      options[:in].include?(val)
    end ? fail : pass
  elsif !options[:set] && options[:in].include?(attribute_value)
    fail
  else
    pass
  end
end