Sha256: 93ea453b1138b860f579ca89a8991188fea9822932748866db46defb18cdd30e

Contents?: true

Size: 1.33 KB

Versions: 48

Compression:

Stored size: 1.33 KB

Contents

require 'incline/number_formats'
require 'active_record'

module Incline::Extensions

  ##
  # Patches the ActiveRecord Float value type to accept more numbers.
  #
  # Specifically this will allow comma delimited numbers to be provided to active record models.
  module FloatValue

    ##
    # Patches the ActiveRecord Float value type.
    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

  end

end

ActiveRecord::Type::Float.include Incline::Extensions::FloatValue

Version data entries

48 entries across 48 versions & 1 rubygems

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