Sha256: 034e2aede434ef527fa19cf1772bd5594fb06251a36abfda7e324f128e628c53

Contents?: true

Size: 1001 Bytes

Versions: 23

Compression:

Stored size: 1001 Bytes

Contents

# frozen_string_literal: true
require 'store_as_int'

module BetterRecord
  module MoneyInteger
    module TableDefinition
      def money_integer(*args, **opts)
        args.each do |name|
          column name, :money_integer, **opts
        end
      end
    end

    class Type < ActiveRecord::Type::Value
      def cast(value)
        convert_to_money(value)
      end

      def deserialize(value)
        super(convert_to_money(value))
      end

      def serialize(value)
        super(convert_to_money(value).value)
      end

      private
        def convert_to_money(value)
          return StoreAsInt::Money.new(0) unless value
          if (!value.kind_of?(Numeric))
            begin
              dollars_to_cents = (value.gsub(/\$/, '').presence || 0).to_d * 100
              StoreAsInt.money(dollars_to_cents.to_i)
            rescue
              StoreAsInt::Money.new
            end
          else
            StoreAsInt.money(value)
          end
        end
    end
  end
end

Version data entries

23 entries across 23 versions & 1 rubygems

Version Path
better_record-0.17.4 lib/better_record/money_integer.rb
better_record-0.17.3 lib/better_record/money_integer.rb
better_record-0.17.1 lib/better_record/money_integer.rb
better_record-0.17.0 lib/better_record/money_integer.rb
better_record-0.16.1 lib/better_record/money_integer.rb
better_record-0.16.0 lib/better_record/money_integer.rb
better_record-0.15.2 lib/better_record/money_integer.rb
better_record-0.15.1 lib/better_record/money_integer.rb
better_record-0.15.0 lib/better_record/money_integer.rb
better_record-0.14.6 lib/better_record/money_integer.rb
better_record-0.14.5 lib/better_record/money_integer.rb
better_record-0.14.4 lib/better_record/money_integer.rb
better_record-0.14.3 lib/better_record/money_integer.rb
better_record-0.14.2 lib/better_record/money_integer.rb
better_record-0.14.1 lib/better_record/money_integer.rb
better_record-0.14.0 lib/better_record/money_integer.rb
better_record-0.13.1 lib/better_record/money_integer.rb
better_record-0.13.0 lib/better_record/money_integer.rb
better_record-0.12.5 lib/better_record/money_integer.rb
better_record-0.12.4 lib/better_record/money_integer.rb