Class: Anodator::Validator::NumericValidator

Inherits:
Base
  • Object
show all
Defined in:
lib/anodator/validator/numeric_validator.rb

Instance Attribute Summary

Attributes inherited from Base

#options, #target

Instance Method Summary collapse

Methods inherited from Base

#allow_blank?, #argument_value_at, default_options, #description, #target_value, #to_s, #valid?, valid_option_keys, #validate_configuration, values, values=

Constructor Details

#initialize(target_expression, options = { }) ⇒ NumericValidator

Returns a new instance of NumericValidator.



11
12
13
14
15
16
17
18
19
# File 'lib/anodator/validator/numeric_validator.rb', line 11

def initialize(target_expression, options = { })
  super(target_expression, options)

  [:greater_than, :greater_than_or_equal_to,
    :less_than, :less_than_or_equal_to,
    :equal_to, :not_equal_to].each do |key|
    @options[key] = proxy_value(@options[key]) unless @options[key].nil?
  end
end

Instance Method Details

#validateObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/anodator/validator/numeric_validator.rb', line 21

def validate
  if allow_blank?
    return true if target_value.split(//).size.zero?
  end

  # check format
  if @options[:only_integer]
    regexp = /^-?\d+$/
  else
    regexp = /^-?\d+(\.\d+)?$/
  end
  return false unless regexp.match target_value

  # convert BigDecimal value
  value = BigDecimal.new(target_value)

  @options.each do |option, configuration|
    case option
    when :greater_than
      return false unless value > BigDecimal.new(configuration.value.to_s)
    when :greater_than_or_equal_to
      return false unless value >= BigDecimal.new(configuration.value.to_s)
    when :less_than
      return false unless value < BigDecimal.new(configuration.value.to_s)
    when :less_than_or_equal_to
      return false unless value <= BigDecimal.new(configuration.value.to_s)
    when :equal_to
      return false unless value == BigDecimal.new(configuration.value.to_s)
    when :not_equal_to
      return false unless value != BigDecimal.new(configuration.value.to_s)
    end
  end

  return true
end