Introduction
O hai!
Features
-
State transitions validation.
-
State-scoped validations.
-
State-scoped lifecycle callbacks (before|after_save, etc)
-
???????
-
PROFIT!!!11
As a bonus you get multiple conditions in :if|:unless => [:one, :two, ...]
callback and validation options (as in edge Rails).
Installation
gem install pipa-statelogic --source http://gems.github.com
Installable as a plugin too.
Bugs & such
Please report via Github issue tracking.
Hint: If you feel like generous today you can tip me at tipjoy.com/u/pisuka
Example
class Order < ActiveRecord::Base
...
statelogic :attribute => :state do # +:state+ is the default value, may be omitted
# you get methods +unpaid?+ and +was_unpaid?+.
# may be more than one initial state.
initial_state 'unpaid' do
transitions_to 'ready', 'suspended' # won't let you change to wrong states
end
state 'ready' do # you get +ready?+, +was_ready?+
transitions_to 'redeemed', 'suspended'
validates_presence_of :txref # scoped validations
before_save :prepare_for_plucking # scoped callbacks
end
state 'redeemed' do # likewise
transitions_to 'suspended'
validates_presence_of :txref, :redeemed_at, :facility_id # scoped validations
end
state 'suspended' do # you guess
transitions_to 'unpaid', 'ready', 'redeemed'
validate do |order|
order.errors.add(:txref, :invalid) if order.txref && order.txref !~ /\AREF/
end
end
end
...
end
order = Order.new
order.state = 'wtf'
order.txref = 'orly'
order.valid? # Please note that state transition checks are done during
# the validation step as well, and the error is added to
# the model's +errors+ collection on the state column and
# will appear on your form. Standard ActiveRecord's error
# message +:inclusion+ is used. Override it with Rails i18n
# for something more specific if it's to be displayed to user.
Copyright © 2009 Igor Gunko, released under the MIT license