1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-02-17 11:54:22 +01:00

refactoring wallet amount to concern

This commit is contained in:
Peng DU 2016-07-05 12:30:52 +02:00
parent 9116e8c04a
commit 1dab903054
4 changed files with 29 additions and 10 deletions

View File

@ -0,0 +1,23 @@
module AmountConcern
extend ActiveSupport::Concern
included do
validates_numericality_of :amount, greater_than_or_equal_to: 0
def amount=(amount)
if amount.nil?
write_attribute(:amount, amount)
else
write_attribute(:amount, amount.to_i * 100)
end
end
def amount
if read_attribute(:amount).blank?
read_attribute(:amount)
else
read_attribute(:amount) / 100.0
end
end
end
end

View File

@ -1,16 +1,10 @@
class Wallet < ActiveRecord::Base
include AmountConcern
belongs_to :user
has_many :wallet_transactions, dependent: :destroy
validates :user, presence: true
validates_numericality_of :amount, greater_than_or_equal_to: 0
def amount=(amount)
write_attribute(:amount, amount.to_i * 100)
end
def amount
read_attribute(:amount) / 100.0
end
def credit(amount)
if amount.is_a?(Numeric) and amount >= 0

View File

@ -1,4 +1,6 @@
class WalletTransaction < ActiveRecord::Base
include AmountConcern
belongs_to :user
belongs_to :wallet
belongs_to :reservation

View File

@ -2,7 +2,7 @@ require 'test_helper'
class WalletTransactionTest < ActiveSupport::TestCase
test 'transaction type must be credit or debit' do
transaction = WalletTransaction.new
transaction = WalletTransaction.new amount: 5
transaction.transaction_type = 'credit'
assert transaction.valid?
transaction.transaction_type = 'debit'