class Mongoid::Matchers::Validations::ValidateNumericalityOfMatcher

Constants

ALLOWED_OPTIONS

Public Class Methods

new(field) click to toggle source
# File lib/matchers/validations/numericality_of.rb, line 19
def initialize(field)
  super(field, :numericality)
  @options = {}
end

Public Instance Methods

description() click to toggle source
# File lib/matchers/validations/numericality_of.rb, line 51
def description
  super << options_message(@options)
end
matches?(actual) click to toggle source
# 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) click to toggle source
# 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.has_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

Protected Instance Methods

method_missing(m, *args, &block) click to toggle source
Calls superclass method
# 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
options_message(options) click to toggle source
# File lib/matchers/validations/numericality_of.rb, line 57
def options_message(options)
  type_msg = []
  comp_msg = []
  options.each_pair do |key, value|
    case key
    when :allow_nil
    when :only_integer
      type_msg << "integer" if value
    when :odd, :even
      type_msg << "#{key.to_s}-numbered" if value
    else
      comp_msg << "#{key.to_s.gsub("_", " ")} #{value.inspect}"
    end
  end
  allow_nil = (options[:allow_nil] ? "nil" : "non-nil") if options.has_key?(:allow_nil)
  ["", "allowing", allow_nil, type_msg.any? ? type_msg.to_sentence : nil, "values", comp_msg.any? ? comp_msg.to_sentence : nil].compact.join(" ")
end