-
Notifications
You must be signed in to change notification settings - Fork 206
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Provide a working example for #63 Recommendation for undoing an event
- Loading branch information
Showing
1 changed file
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |