Module: Incline::Extensions::DecimalValue

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

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



8
9
10
11
12
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/decimal_value.rb', line 8

def self.included(base)
  base.class_eval do
    private

    undef cast_value

    def cast_value(value)
      begin
        casted_value =
            case value
              when ::Float
                convert_float_to_big_decimal(value)
              when ::String
                # 1,234.56789e0
                if value =~ Incline::NumberFormats::WITH_DELIMITERS
                  value = value.gsub(',', '')
                end
                if value =~ Incline::NumberFormats::WITHOUT_DELIMITERS
                  BigDecimal(value, precision.to_i)
                else
                  nil
                end
              when ::Numeric
                BigDecimal(value, precision.to_i)
              else
                if value.respond_to?(:to_d)
                  value.to_d
                else
                  cast_value(value.to_s)
                end
            end

        apply_scale(casted_value) if casted_value
      rescue
        Incline::Log::warn "Failed to parse #{value.inspect}: #{$!.message}"
        nil
      end
    end


  end
end