diff --git a/CHANGELOG.md b/CHANGELOG.md index ace51ae..1fc3d42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,10 @@ * deprecated old aasm_* class methods (old-style DSL), in preparation for AASM v4.0.0 +## 3.4.0 + + * allow retrieving the current event (`aasm.current_event`) (see [issue #159](https://github.com/aasm/aasm/issues/159) and [issue #168](https://github.com/aasm/aasm/issues/168)) + ## 3.3.3 * bugfix: support reloading development environment in Rails (see [issue #148](https://github.com/aasm/aasm/issues/148)) diff --git a/README.md b/README.md index 320252a..979811e 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,31 @@ originating state (the from-state) and the target state (the to state), like thi end ``` +#### The current event triggered + +While running the callbacks you can easily retrieve the name of the event triggered +by using `aasm.current_event`: + +```ruby + # taken the example callback from above + def do_something + puts "triggered #{aasm.current_event}" + end +``` + +and then + +```ruby + job = Job.new + + # without bang + job.sleep # => triggered :sleep + + # with bang + job.sleep! # => triggered :sleep! +``` + + ### Guards Let's assume you want to allow particular transitions only if a defined condition is diff --git a/lib/aasm/base.rb b/lib/aasm/base.rb index 625c244..9198f09 100644 --- a/lib/aasm/base.rb +++ b/lib/aasm/base.rb @@ -65,10 +65,12 @@ module AASM end @klass.send(:define_method, "#{name.to_s}!") do |*args, &block| + aasm.current_event = "#{name.to_s}!".to_sym aasm_fire_event(name, {:persist => true}, *args, &block) end @klass.send(:define_method, "#{name.to_s}") do |*args, &block| + aasm.current_event = name.to_sym aasm_fire_event(name, {:persist => false}, *args, &block) end end diff --git a/lib/aasm/instance_base.rb b/lib/aasm/instance_base.rb index deaf33f..b0ee17e 100644 --- a/lib/aasm/instance_base.rb +++ b/lib/aasm/instance_base.rb @@ -1,7 +1,7 @@ module AASM class InstanceBase - attr_accessor :from_state, :to_state + attr_accessor :from_state, :to_state, :current_event def initialize(instance) @instance = instance diff --git a/lib/aasm/version.rb b/lib/aasm/version.rb index b5df3af..5e55fd7 100644 --- a/lib/aasm/version.rb +++ b/lib/aasm/version.rb @@ -1,3 +1,3 @@ module AASM - VERSION = "3.3.3" + VERSION = "3.4.0" end diff --git a/spec/unit/event_spec.rb b/spec/unit/event_spec.rb index e8b3f73..939596b 100644 --- a/spec/unit/event_spec.rb +++ b/spec/unit/event_spec.rb @@ -244,6 +244,24 @@ describe 'should fire callbacks' do end end +describe 'current event' do + let(:pe) {ParametrisedEvent.new} + + it 'if no event has been triggered' do + expect(pe.aasm.current_event).to be_nil + end + + it 'if a event has been triggered' do + pe.wakeup + expect(pe.aasm.current_event).to eql :wakeup + end + + it 'if no event has been triggered' do + pe.wakeup! + expect(pe.aasm.current_event).to eql :wakeup! + end +end + describe 'parametrised events' do let(:pe) {ParametrisedEvent.new}