Skip to content

Commit

Permalink
allow retrieving the current event (see #159 and #168)
Browse files Browse the repository at this point in the history
  • Loading branch information
alto committed Sep 12, 2014
1 parent 25fd16a commit 0adf6c5
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,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))
Expand Down
25 changes: 25 additions & 0 deletions README.md
Expand Up @@ -163,6 +163,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
Expand Down
2 changes: 2 additions & 0 deletions lib/aasm/base.rb
Expand Up @@ -55,10 +55,12 @@ def event(name, options={}, &block)
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
Expand Down
2 changes: 1 addition & 1 deletion 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
Expand Down
18 changes: 18 additions & 0 deletions spec/unit/event_spec.rb
Expand Up @@ -244,6 +244,24 @@
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}

Expand Down

0 comments on commit 0adf6c5

Please sign in to comment.