Class: Mongoid::Matchers::Validations::ValidateNumericalityOfMatcher

Inherits:
HaveValidationMatcher show all
Defined in:
lib/matchers/validations/numericality_of.rb

Constant Summary collapse

@@allowed_options =
[:equal_to, :greater_than, :greater_than_or_equal_to, :less_than, :less_than_or_equal_to, 
:even, :odd, :only_integer, :allow_nil, :nil]

Instance Method Summary collapse

Methods inherited from HaveValidationMatcher

#failure_message_for_should, #failure_message_for_should_not

Constructor Details

#initialize(field) ⇒ ValidateNumericalityOfMatcher

Returns a new instance of ValidateNumericalityOfMatcher.



8
9
10
11
# File 'lib/matchers/validations/numericality_of.rb', line 8

def initialize(field)
  super(field, :numericality)
  @options = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object (protected)



59
60
61
62
63
64
65
66
# File 'lib/matchers/validations/numericality_of.rb', line 59

def method_missing(m, *args, &block)
  if @@allowed_options.include?(m.to_sym)
    raise ArgumentError, "wrong number of arguments (#{args.length} for 1)" if args.length > 1
    send :to_allow, m.to_sym => args.first
  else
    super
  end
end

Instance Method Details

#descriptionObject



35
36
37
# File 'lib/matchers/validations/numericality_of.rb', line 35

def description
  super << options_message(@options)
end

#matches?(actual) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/matchers/validations/numericality_of.rb', line 22

def matches?(actual)
  return false unless result = super(actual)
  
  @@allowed_options.each do |comparator|
    if @options.has_key?(comparator) and !([:even, :odd, :only_integer].include?(comparator) and !@validator.options.include?(comparator))
      result &= (@validator.options[comparator] == @options[comparator])
    end
  end
  @positive_result_message <<= options_message(@validator.options)
  @negative_result_message <<= options_message(@validator.options)
  result
end

#to_allow(options) ⇒ Object

Raises:

  • (ArgumentError)


13
14
15
16
17
18
19
20
# File 'lib/matchers/validations/numericality_of.rb', line 13

def to_allow(options)
  options[:equal_to] = options if options.is_a?(Numeric)
  options[:allow_nil] = options.delete(:nil) if options.has_key?(:nil)
  raise ArgumentError, "validate_numericality_of#to_allow requires a Hash parameter containing any of the following keys: " <<
    @@allowed_options.map(&:inspect).join(", ") if !options.is_a?(Hash) or options.empty? or (options.keys - @@allowed_options).any?
  @options.merge!(options)
  self
end