Class: NoBrainer::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.



21
22
23
24
# File 'lib/matchers/validations/numericality_of.rb', line 21

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)



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

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



53
54
55
# File 'lib/matchers/validations/numericality_of.rb', line 53

def description
  "#{super}#{options_message(@options)}"
end

#matches?(actual) ⇒ Boolean

Returns:

  • (Boolean)


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

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



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

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