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

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

Constant Summary collapse

ALLOWED_OPTIONS =
%i[
  allow_nil
  equal_to
  even
  greater_than
  greater_than_or_equal_to
  less_than
  less_than_or_equal_to
  nil
  odd
  only_integer
].freeze

Instance Method Summary collapse

Methods inherited from HaveValidationMatcher

#failure_message_for_should, #failure_message_for_should_not, #on, #with_message

Constructor Details

#initialize(field) ⇒ ValidateNumericalityOfMatcher

Returns a new instance of ValidateNumericalityOfMatcher.



19
20
21
22
# File 'lib/matchers/validations/numericality_of.rb', line 19

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)



75
76
77
78
79
80
81
82
# File 'lib/matchers/validations/numericality_of.rb', line 75

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



51
52
53
# File 'lib/matchers/validations/numericality_of.rb', line 51

def description
  super << options_message(@options)
end

#matches?(actual) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
43
44
45
46
47
48
49
# File 'lib/matchers/validations/numericality_of.rb', line 39

def matches?(actual)
  return false unless result = super(actual)

  @options.each do |comparator, expected_value|
    result &= (@validator.options[comparator] == expected_value)
  end

  @positive_result_message <<= options_message(@validator.options)
  @negative_result_message <<= options_message(@validator.options)
  result
end

#to_allow(options) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/matchers/validations/numericality_of.rb', line 24

def to_allow(options)
  options[:equal_to] = options if options.is_a?(Numeric)
  options[:allow_nil] = options.delete(:nil) if options.key?(:nil)

  if !options.is_a?(Hash) || options.empty? || (options.keys - ALLOWED_OPTIONS).any?
    message =
      'validate_numericality_of#to_allow requires a Hash parameter containing' \
      "any of the following keys: #{ALLOWED_OPTIONS.map(&:inspect).join(', ')}"
    raise ArgumentError, message
  end

  @options.merge!(options)
  self
end