module Incline::Extensions::FloatValue

Patches the ActiveRecord Float value type to accept more numbers.

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

Public Class Methods

included(base) click to toggle source

Patches the ActiveRecord Float value type.

# File lib/incline/extensions/float_value.rb, line 14
def self.included(base)

  base.class_eval do
    private

    undef cast_value

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

  end

end

Public Instance Methods

cast_value(value) click to toggle source
# File lib/incline/extensions/float_value.rb, line 21
def cast_value(value)
  begin
    case value
      when true
        1.0
      when false
        0.0
      when ::String
        # 1,234.56789
        if value =~ Incline::NumberFormats::WITH_DELIMITERS
          value = value.gsub(',', '')
        end
        if value =~ Incline::NumberFormats::WITHOUT_DELIMITERS
          value.to_f
        else
          nil
        end
      else
        if value.respond_to?(:to_f)
          value.to_f
        else
          nil
        end
    end
  rescue
    Incline::Log::warn "Failed to parse #{value.inspect}: #{$!.message}"
    nil
  end
end