Skip to content

Instantly share code, notes, and snippets.

@mryoshio
Last active December 19, 2015 11:29
Show Gist options
  • Select an option

  • Save mryoshio/5948392 to your computer and use it in GitHub Desktop.

Select an option

Save mryoshio/5948392 to your computer and use it in GitHub Desktop.
use state_machine
# sample class
class Book < ActiveRecord::Base
attr_accessible :author, :status, :title
state_machine :status, :initial => :draft do
state :draft, :public, :suspending, :archived
state :draft do
def published?; false end
end
state :public, :suspending, :archived do
def published?; true end
end
event :rewrite do
transition :public => :draft
end
event :publish do
transition :draft => :public
end
event :suspend do
transition :public => :suspending
end
event :archive do
transition :suspending => :archived
end
end
end
# usage
irb(main):024:0> b = Book.new
=> #<Book id: nil, title: nil, author: nil, status: "draft", created_at: nil, updated_at: nil>
irb(main):070:0> b.published?
=> false
irb(main):025:0> b.publish
=> true
irb(main):026:0> b.status
=> "public"
irb(main):074:0> b.published?
=> true
irb(main):027:0> b.rewrite
irb(main):028:0> b.status
=> "draft"
irb(main):030:0> b.status_events
=> [:publish]
irb(main):031:0> b.archive
=> false
irb(main):032:0> b.status
=> "draft"
irb(main):033:0> b.publish
=> true
irb(main):034:0> b.archive
=> false
irb(main):035:0> b.status
=> "public"
irb(main):036:0> b.suspend
irb(main):037:0> b.status_events
=> [:archive]
irb(main):038:0> b.archive
irb(main):039:0> b.status
=> "archived"
irb(main):040:0> b.published?
=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment