Skip to content

Commit

Permalink
Provide a working example for #63 Recommendation for undoing an event
Browse files Browse the repository at this point in the history
  • Loading branch information
geekq committed Jan 20, 2013
1 parent c9aa08c commit 2af759f
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions test/advanced_examples_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
require File.join(File.dirname(__FILE__), 'test_helper')
require 'workflow'
class AdvanceExamplesTest < ActiveRecordTestCase

class Article
include Workflow
workflow do
state :new do
event :submit, :transitions_to => :awaiting_review
end
state :awaiting_review do
event :review, :transitions_to => :being_reviewed
end
state :being_reviewed do
event :accept, :transitions_to => :accepted
event :reject, :transitions_to => :rejected
end
state :accepted do
end
state :rejected do
end
end
end

test '#63 undoing event - automatically add revert events for every defined event' do
# also see https://github.com/geekq/workflow/issues/63
spec = Article.workflow_spec
spec.state_names.each do |state_name|
state = spec.states[state_name]

(state.events.values.reject {|e| e.name.to_s =~ /^revert_/ }).each do |event|
event_name = event.name
revert_event_name = "revert_" + event_name.to_s

# Add revert events
spec.states[event.transitions_to.to_sym].events[revert_event_name.to_sym] =
Workflow::Event.new(revert_event_name, state, {})

# Add methods for revert events
Article.module_eval do
define_method "#{revert_event_name}!".to_sym do |*args|
process_event!(revert_event_name, *args)
end
define_method "can_#{revert_event_name}?" do
return self.current_state.events.include?(revert_event_name)
end
end

end
end

a = Article.new
assert(a.new?, "should start with the 'new' state")
a.submit!
assert(a.awaiting_review?, "should now be in 'awaiting_review' state")
assert_equal(['revert_submit', 'review'], a.current_state.events.keys.map(&:to_s).sort)
a.revert_submit! # this method is added by our meta programming magic above
assert(a.new?, "should now be back in the 'new' state")
end

end

0 comments on commit 2af759f

Please sign in to comment.