Sha256: f7036e8fd4806cc33f39ba30967dd6cc52b6a0497b4e162c9b4041d11dc989a8

Contents?: true

Size: 729 Bytes

Versions: 17

Compression:

Stored size: 729 Bytes

Contents

class MoneyType < ActiveRecord::Type::Value
  def cast(value)
    return nil unless value
    convert_to_money(value)
  end

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

  def serialize(value)
    new_val = convert_to_money(value)
    super(new_val ? new_val.value : nil)
  end

  private
    def convert_to_money(value)
      return nil 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

ActiveRecord::Type.register(:money_column, MoneyType)

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
better_record-0.8.0 config/initializers/active_record/money_type.rb
better_record-0.7.5 config/initializers/active_record/money_type.rb
better_record-0.7.4 config/initializers/active_record/money_type.rb
better_record-0.7.3 config/initializers/active_record/money_type.rb
better_record-0.7.2 config/initializers/active_record/money_type.rb
better_record-0.7.1 config/initializers/active_record/money_type.rb
better_record-0.7.0 config/initializers/active_record/money_type.rb
better_record-0.6.1 config/initializers/active_record/money_type.rb
better_record-0.6.0 config/initializers/active_record/money_type.rb
better_record-0.5.5 config/initializers/active_record/money_type.rb
better_record-0.5.4 config/initializers/active_record/money_type.rb
better_record-0.5.1 config/initializers/active_record/money_type.rb
better_record-0.5.0 config/initializers/active_record/money_type.rb
better_record-0.4.0 config/initializers/active_record/money_type.rb
better_record-0.3.0 config/initializers/active_record/money_type.rb
better_record-0.2.0 config/initializers/active_record/money_type.rb
better_record-0.1.1 config/initializers/money_type.rb