Class: NotNaughty::AcceptanceValidation

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

Overview

Validates acceptance of obj’s attribute against a fixed value via :eql? call.

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

Options:

:accept

object to check against (via :eql?)

:message

see NotNaughty::Errors for details

:if

see NotNaughty::Validation::Condition for details

:unless

see NotNaughty::Validation::Condition for details

Example:

invalid = 'abc'
valid = '1'
def invalid.errors() @errors ||= NotNauthy::Errors.new end
def valid.errors() @errors ||= NotNauthy::Errors.new end

AcceptanceValidation.new({}, :to_s).call invalid, :to_s, 'abc'
invalid.errors.on(:to_s).any? # => true

AcceptanceValidation.new({}, :to_s).call valid, :to_s, '1'
valid.errors.on(:to_s).any? # => false

Constant Summary

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(opts, attributes) ⇒ AcceptanceValidation

:nodoc:



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/not_naughty/validations/acceptance_validation.rb', line 28

def initialize(opts, attributes) #:nodoc:
  __message, __accept =
    opts[:message] || '#{"%s".humanize} not accepted.',
    opts[:accept] || '1'

  if opts[:allow_blank] or opts.fetch(:allow_nil, true)
    __allow = if opts[:allow_blank] then :blank? else :nil? end
    super opts, attributes do |o, a, v|
      o.errors.add a, __message unless v.send __allow or __accept.eql? v
    end
  else
    super opts, attributes do |o, a, v|
      o.errors.add a, __message unless __accept.eql? v
    end
  end
end