# AASM is a continuation of the acts-as-state-machine rails plugin, built for plain Ruby objects. gem 'aasm','~> 4.12','>= 4.12.0'
instance method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
## # check status ##
job.running?# => true job.may_run?# => false
job.aasm.current_state # stage3 job.aasm_state # => 'sleeping' job.aasm.human_state # => 'sleeping' job.aasm.states(:permitted =>true).map(&:name)# show all permitted states (from initial state) job.aasm.states(:permitted =>false).map(&:name)# show all non permitted states job.aasm.events.map(&:name)# show all possible (triggerable) events from the current state
# ./OnePageShop/app/models/order.rb classOrder<ApplicationRecord # Concerns macros include AASM
# Attributes related macros aasm column:'status', no_direct_assignment:true, requires_lock:truedo # 等待付款 state :waiting_for_payment, initial:true # 已付款 state :paid # 已出貨 state :shipped # 訂單逾期 state :expired # 已退款 state :refunded
# ./OnePageShop/app/models/transaction.rb classTransaction<ApplicationRecord # Concerns macros include AASM
# Attributes related macros aasm column:'status', no_direct_assignment:true, requires_lock:truedo # 等待繳款 state :waiting_for_payment, initial:true # 已付款 state :paid # 交易失敗 state :failed # 取消 state :canceled # 逾期 state :expired # 已退款 state :refunded
ifself.paid? # set all waiting for payment transaction as canceled self.order.transactions.waiting_for_payment.each do|transaction| transaction.mark_as_canceled!if transaction.may_mark_as_canceled? end
self.order.mark_as_paid!ifself.order.may_mark_as_paid? end end
def check_all_transactions_refunded! # 若沒有其餘等待付款或已付款的交易,則將訂單狀態改為已退款 if!Transaction.where(order_id:self.order_id, status:%i(waiting_for_payment paid)).exists? self.order.mark_as_refunded! end end end