Class: DataMapper::Validate::WithinValidator

Inherits:
GenericValidator show all
Defined in:
lib/dm-validations/validators/within_validator.rb

Overview

Author:

  • Guy van den Berg

Since:

  • 0.9

Instance Attribute Summary

Attributes inherited from GenericValidator

#field_name, #humanized_field_name, #if_clause, #options, #unless_clause

Instance Method Summary collapse

Methods inherited from GenericValidator

#==, #add_error, #execute?, #inspect

Constructor Details

#initialize(field_name, options = {}) ⇒ WithinValidator

Returns a new instance of WithinValidator.

Since:

  • 0.9



10
11
12
13
14
# File 'lib/dm-validations/validators/within_validator.rb', line 10

def initialize(field_name, options={})
  super

  @options[:set] = [] unless @options.has_key?(:set)
end

Instance Method Details

#call(target) ⇒ Object

Since:

  • 0.9



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/dm-validations/validators/within_validator.rb', line 16

def call(target)
  value = target.send(field_name)
  return true if @options[:allow_nil] && value.blank?
  return true if @options[:set].include?(value)

  set = @options[:set]
  msg = @options[:message]
  if set.is_a?(Range)
    if set.first != -n && set.last != n
      error_message = msg || ValidationErrors.default_error_message(:value_between, field_name, set.first, set.last)
    elsif set.first == -n
      error_message = msg || ValidationErrors.default_error_message(:less_than_or_equal_to, field_name, set.last)
    elsif set.last == n
      error_message = msg || ValidationErrors.default_error_message(:greater_than_or_equal_to, field_name, set.first)
    end
  else
    error_message = msg || ValidationErrors.default_error_message(:inclusion, field_name, set.join(', '))
  end

  add_error(target, error_message, field_name)
  return false
end

#nObject

Since:

  • 0.9



39
40
41
# File 'lib/dm-validations/validators/within_validator.rb', line 39

def n
  1.0/0
end