Class: Aequitas::Rule::Numericalness

Inherits:
Aequitas::Rule show all
Defined in:
lib/aequitas/rule/numericalness.rb,
lib/aequitas/rule/numericalness/integer.rb,
lib/aequitas/rule/numericalness/non_integer.rb

Direct Known Subclasses

Integer, NonInteger

Defined Under Namespace

Classes: Integer, NonInteger

Instance Attribute Summary collapse

Attributes inherited from Aequitas::Rule

#attribute_name, #custom_message, #guard, #skip_condition

Attributes included from ValueObject

#equalizer

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Aequitas::Rule

#attribute_value, #execute?, #initialize, #skip?, #validate, #violation_data, #violation_info, #violation_values

Methods included from ValueObject

#equalize_on

Constructor Details

This class inherits a constructor from Aequitas::Rule

Instance Attribute Details

#expectedObject (readonly)

Returns the value of attribute expected



24
25
26
# File 'lib/aequitas/rule/numericalness.rb', line 24

def expected
  @expected
end

Class Method Details

.rules_for(attribute_name, options) ⇒ Object

TODO: move options normalization into the validator macros?



15
16
17
18
19
20
21
22
# File 'lib/aequitas/rule/numericalness.rb', line 15

def self.rules_for(attribute_name, options)
  int = options.values_at(:only_integer, :integer_only).compact.first

  rules = []
  rules << Integer.new(attribute_name, options)    if int
  rules << NonInteger.new(attribute_name, options) if !int
  rules
end

Instance Method Details

#valid_numericalness?(value) ⇒ Boolean



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/aequitas/rule/numericalness.rb', line 34

def valid_numericalness?(value)
  # XXX: workaround for jruby. This is needed because the jruby
  # compiler optimizes a bit too far with magic variables like $~.
  # the value.send line sends $~. Inserting this line makes sure the
  # jruby compiler does not optimise here.
  # see http://jira.codehaus.org/browse/JRUBY-3765
  $~ = nil if RUBY_PLATFORM[/java/]

  value_as_string(value) =~ expected
rescue ArgumentError
  # TODO: figure out better solution for: can't compare String with Integer
  true
end

#valid_value?(value) ⇒ Boolean



26
27
28
29
30
31
32
# File 'lib/aequitas/rule/numericalness.rb', line 26

def valid_value?(value)
  # TODO: is it even possible for expected to be nil?
  #   if so, return a dummy validator when expected is nil
  return true if expected.nil?

  skip?(value) || valid_numericalness?(value)
end

#value_as_string(value) ⇒ Object



48
49
50
51
52
53
54
55
56
# File 'lib/aequitas/rule/numericalness.rb', line 48

def value_as_string(value)
  case value
  # Avoid Scientific Notation in Float to_s
  when Float      then value.to_d.to_s('F')
  when BigDecimal then value.to_s('F')
  when Rational   then value_as_string(value.to_f)
  else value.to_s
  end
end