Class: WhyValidationsSuckIn96::ValidatesInclusion

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

Overview

Checks the validity of an attribute against a list of values for it to be included in.

Examples:

Default usage

setup_validations do
  validates_inclusion_of :unit_system, :in => %w[imperial metric]
end

Usage when checking a set of values against another set

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

Constant Summary collapse

DefaultOptions =
{:message => "is not in the acceptable 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 = {}) ⇒ ValidatesInclusion

Returns a new instance of ValidatesInclusion.

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 inclusion.

  • :set (true, false)

    Whether or not to do a set based comparison

Raises:

  • (ArgumentError)


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

def initialize(validatable, options = {})
  super
  raise(ArgumentError, "Collection to check for inclusion 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_inclusion.rb', line 34

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