Sha256: de3628ae124ad2b18b170e2043de9060084af86f85049086238f4f37e3e6fc65

Contents?: true

Size: 1.38 KB

Versions: 48

Compression:

Stored size: 1.38 KB

Contents

require 'incline/number_formats'
require 'active_record'

module Incline::Extensions

  module DecimalValue

    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

  end

end

ActiveRecord::Type::Decimal.include Incline::Extensions::DecimalValue

Version data entries

48 entries across 48 versions & 1 rubygems

Version Path
incline-0.3.14 lib/incline/extensions/decimal_value.rb
incline-0.3.13 lib/incline/extensions/decimal_value.rb
incline-0.3.12 lib/incline/extensions/decimal_value.rb
incline-0.3.11 lib/incline/extensions/decimal_value.rb
incline-0.3.10 lib/incline/extensions/decimal_value.rb
incline-0.3.9 lib/incline/extensions/decimal_value.rb
incline-0.3.8 lib/incline/extensions/decimal_value.rb
incline-0.3.7 lib/incline/extensions/decimal_value.rb
incline-0.3.6 lib/incline/extensions/decimal_value.rb
incline-0.3.5 lib/incline/extensions/decimal_value.rb
incline-0.3.4 lib/incline/extensions/decimal_value.rb
incline-0.3.3 lib/incline/extensions/decimal_value.rb
incline-0.3.2 lib/incline/extensions/decimal_value.rb
incline-0.3.1 lib/incline/extensions/decimal_value.rb
incline-0.3.0 lib/incline/extensions/decimal_value.rb
incline-0.2.36 lib/incline/extensions/decimal_value.rb
incline-0.2.35 lib/incline/extensions/decimal_value.rb
incline-0.2.34 lib/incline/extensions/decimal_value.rb
incline-0.2.28 lib/incline/extensions/decimal_value.rb
incline-0.2.27 lib/incline/extensions/decimal_value.rb