|
- # == Schema Information
- #
- # Table name: wallets
- #
- # id :integer not null, primary key
- # balance :integer
- # user_id :integer
- # created_at :datetime not null
- # updated_at :datetime not null
- #
-
- class Wallet < ApplicationRecord
- belongs_to :user
- has_many :outcome, class_name: 'CoinChange', foreign_key: 'from_wallet_id', dependent: :destroy
- has_many :income, class_name: 'CoinChange', foreign_key: 'to_wallet_id', dependent: :destroy
- validates :balance, presence: true
- @@wallet_lock = Mutex.new
-
- def receive(amount)
- with_lock do
- self.balance += amount
- save!
- end
- end
-
- def pay(amount)
- with_lock do
- if self.balance < amount
- reload
- return false
- else
- self.balance -= amount
- save!
- end
- end
- true
- end
-
- def self.wallet_lock
- @@wallet_lock
- end
- end
|