Skip to content

Instantly share code, notes, and snippets.

@brentkirby
Created March 5, 2012 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brentkirby/1976318 to your computer and use it in GitHub Desktop.
Save brentkirby/1976318 to your computer and use it in GitHub Desktop.
state_machine rails 3.2.2
module EntryUtils
module StateMachine
extend ActiveSupport::Concern
included do
before_validation :ensure_default_state, :on => :create
state_machine :initial => :created do
before_transition any => [:published,:approved] do |entry, transition|
if entry.content_empty?
invalidate(entry, "change: ","You cannot #{transition.event} an empty #{entry.class.to_s}.")
throw :halt
end
end
event :publish do
transition created: :published
transition rejected: :published
end
event :approve do
transition published: :approved
end
event :reject do
transition published: :rejected
end
event :duplicate do
transition approved: :created
end
after_transition any => :rejected do
end
after_transition approved: :created do |entry|
entry.working_revision = entry.working_revision + 1
entry.save(:validate => false)
end
# When approved, create a new version.
after_transition any => :approved do |entry|
entry.send :create_new_revision
if entry.working_revision.to_i <= 1
entry.categories.each{ |category| category.increment!(:entry_count) }
end
end
end
end # end sm
end
##
# Makes sure the default state is always "created" and never nil
#
def ensure_default_state
self.state ||= "created" unless self.persisted?
end
# Ensures the requested state change can be performed before
# processing other validations
#
def ensure_valid_transition
self.class.state_machines.transitions(self, :save).perform
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment