Introduction
Statelogic is a yet another take on state management for your models. It’s tailored specially for ActiveRecord and is different from other frameworks in that it has its main goal in scoping validation rules and callbacks depending on the model’s state to emphasis actual model state consistency over merely formal… whatever…
Features
-
State transitions validation.
-
State-scoped validations.
-
State-scoped lifecycle callbacks (before|after_save, etc)
-
???????
-
PROFIT!!!11
Installation
gem install omg-statelogic --source http://gems.github.com
Installable as a plugin too.
Docs
rdoc.info/projects/omg/statelogic
Bugs & such
Please report via Github issue tracking.
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.
See also
-
github.com/omg/threadpool – Thread pool implementation
-
github.com/omg/peanuts – Ruby <-> XML mapping
Hint: If you feel like generous today you can tip me at tipjoy.com/u/pisuka
Copyright © 2009 Igor Gunko, released under the MIT license