📦 statesman/ gocardless
A statesmanlike state machine library.
Открыть на GitHub ↗обновлён 18ч назад
Звёзды
★ 1.9k
Форки
158
За неделю
—
За месяц
—
Рост %
—
Язык
Ruby
Установка и запуск
Installation
To get started, just add Statesman to your Gemfile, and then run bundle:
gem 'statesman', '~> 13.0.0'
Usage
First, create a state machine based on Statesman::Machine:
class OrderStateMachine
include Statesman::Machine
state :pending, initial: true
state :checking_out
state :purchased
state :shipped
state :cancelled
state :failed
state :refunded
transition from: :pending, to: [:checking_out, :cancelled]
transition from: :checking_out, to: [:purchased, :cancelled]
transition from: :purchased, to: [:shipped, :failed]
transition from: :shipped, to: :refunded
guard_transition(to: :checking_out) do |order|
order.products_in_stock?
end
before_transition(from: :checking_out, to: :cancelled) do |order, transition|
order.reallocate_stock
end
before_transition(to: :purchased) do |order, transition|
PaymentService.new(order).submit
end
after_transition(to: :purchased) do |order, transition|
MailerService.order_confirmation(order).deliver
end
end
Then, link it to your model:
class Order < ActiveRecord::Base
has_many :order_transitions, autosave: false
include Statesman::Adapters::ActiveRecordQueries[
transition_class: OrderTransition,
initial_state: :pending
]
def state_machine
@state_machine ||= OrderStateMachine.new(self, transition_class: OrderTransition)
end
end
Next, you'll need to create a further model to represent state transitions:
class OrderTransition < ActiveRecord::Base
include Statesman::Adapters::ActiveRecordTransition
validates :to_state, inclusion: { in: OrderStateMachine.states }
belongs_to :order, inverse_of: :order_transitions
end
Now, you can start working with your state machine:
…
Из README репозитория · полный README на GitHub