diff --git a/lib/aasm.rb b/lib/aasm.rb index 5fa6e4f..a0d07ab 100644 --- a/lib/aasm.rb +++ b/lib/aasm.rb @@ -33,9 +33,9 @@ module AASM end end - def aasm_event(name, &block) + def aasm_event(name, options = {}, &block) unless aasm_events.has_key?(name) - aasm_events[name] = AASM::SupportingClasses::Event.new(name, &block) + aasm_events[name] = AASM::SupportingClasses::Event.new(name, options, &block) end define_method("#{name.to_s}!") do @@ -46,6 +46,9 @@ module AASM end self.aasm_current_state_with_persistence = new_state + + self.send(self.class.aasm_events[name].success) if self.class.aasm_events[name].success + true else if self.respond_to?(:aasm_event_failed) diff --git a/lib/event.rb b/lib/event.rb index 420d0f8..6ec86b5 100644 --- a/lib/event.rb +++ b/lib/event.rb @@ -3,10 +3,11 @@ require File.join(File.dirname(__FILE__), 'state_transition') module AASM module SupportingClasses class Event - attr_reader :name + attr_reader :name, :success - def initialize(name, &block) + def initialize(name, options = {}, &block) @name = name + @success = options[:success] @transitions = [] instance_eval(&block) if block end diff --git a/spec/unit/aasm_spec.rb b/spec/unit/aasm_spec.rb index baf3021..878fa98 100644 --- a/spec/unit/aasm_spec.rb +++ b/spec/unit/aasm_spec.rb @@ -6,7 +6,7 @@ class Foo aasm_state :open aasm_state :closed - aasm_event :close do + aasm_event :close, :success => :success_callback do transitions :to => :closed, :from => [:open] end @@ -17,6 +17,9 @@ class Foo def always_false false end + + def success_callback + end end class Bar @@ -112,6 +115,14 @@ describe AASM, '- event firing with persistence' do foo.aasm_current_state.should == :closed end + it 'should call the success callback if one was provided' do + foo = Foo.new + + foo.should_receive(:success_callback) + + foo.close! + end + it 'should attempt to persist if aasm_write_state is defined' do foo = Foo.new diff --git a/spec/unit/event_spec.rb b/spec/unit/event_spec.rb index 623a3ae..c7c2001 100644 --- a/spec/unit/event_spec.rb +++ b/spec/unit/event_spec.rb @@ -3,10 +3,11 @@ require File.join(File.dirname(__FILE__), '..', 'spec_helper') describe AASM::SupportingClasses::Event do before(:each) do @name = :close_order + @success = :success_callback end def new_event - @event = AASM::SupportingClasses::Event.new(@name) do + @event = AASM::SupportingClasses::Event.new(@name, {:success => @success}) do transitions :to => :closed, :from => [:open, :received] end end @@ -16,6 +17,11 @@ describe AASM::SupportingClasses::Event do @event.name.should == @name end + it 'should set the success option' do + new_event + @event.success.should == @success + end + it 'should create StateTransitions' do AASM::SupportingClasses::StateTransition.should_receive(:new).with({:to => :closed, :from => :open}) AASM::SupportingClasses::StateTransition.should_receive(:new).with({:to => :closed, :from => :received})