From 1dab903054605bab410bf7527dc8f844859e7a00 Mon Sep 17 00:00:00 2001 From: Peng DU Date: Tue, 5 Jul 2016 12:30:52 +0200 Subject: [PATCH] refactoring wallet amount to concern --- app/models/concerns/amount_concern.rb | 23 +++++++++++++++++++++++ app/models/wallet.rb | 12 +++--------- app/models/wallet_transaction.rb | 2 ++ test/models/wallet_transaction_test.rb | 2 +- 4 files changed, 29 insertions(+), 10 deletions(-) create mode 100644 app/models/concerns/amount_concern.rb diff --git a/app/models/concerns/amount_concern.rb b/app/models/concerns/amount_concern.rb new file mode 100644 index 000000000..86b01b443 --- /dev/null +++ b/app/models/concerns/amount_concern.rb @@ -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 diff --git a/app/models/wallet.rb b/app/models/wallet.rb index eca7adf59..da8128eb7 100644 --- a/app/models/wallet.rb +++ b/app/models/wallet.rb @@ -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 diff --git a/app/models/wallet_transaction.rb b/app/models/wallet_transaction.rb index df5868839..4f88f1c10 100644 --- a/app/models/wallet_transaction.rb +++ b/app/models/wallet_transaction.rb @@ -1,4 +1,6 @@ class WalletTransaction < ActiveRecord::Base + include AmountConcern + belongs_to :user belongs_to :wallet belongs_to :reservation diff --git a/test/models/wallet_transaction_test.rb b/test/models/wallet_transaction_test.rb index 3763f85bd..7eac9a4d2 100644 --- a/test/models/wallet_transaction_test.rb +++ b/test/models/wallet_transaction_test.rb @@ -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'