Module: Incline::Extensions::IntegerValue

Defined in:
lib/incline/extensions/integer_value.rb

Overview

Patches the ActiveRecord Integer type to be able to accept more numbers.

Specifically this will allow comma delimited numbers to be provided to active record models.

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object

Patches the ActiveRecord Integer type.



13
14
15
16
17
18
19
20
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
# File 'lib/incline/extensions/integer_value.rb', line 13

def self.included(base) #:nodoc:
  base.class_eval do

    private

    undef cast_value

    def cast_value(value)
      begin
        case value
          when true then 1
          when false then 0
          when ::String
            # 1,234.56789
            if value =~ Incline::NumberFormats::WITH_DELIMITERS
              value = value.gsub(',', '')
            end
            if value =~ Incline::NumberFormats::WITHOUT_DELIMITERS
              value.to_i
            else
              nil
            end
          else
            if value.respond_to?(:to_i)
              value.to_i
            else
              nil
            end
        end
      rescue
        Incline::Log::warn "Failed to parse #{value.inspect}: #{$!.message}"
        nil
      end
    end

  end
end