aasm after callback with argument
Asked Answered
P

4

5

I'm using the aasm (formerly acts_as_state_machine) gem in my rails 4 application. I have something like this on my Post model

  ...
  aasm column: :state do
    state :pending_approval, initial: true
    state :active
    state :pending_removal

    event :accept_approval, :after => Proc.new { |user| binding.pry } do
      transitions from: :pending_approval, to: :active
    end
  end
  ...

When I call @post.accept_approval!(:active, current_user) and the after callback gets triggered, in my console I can inspect what user is (that was passed into the Proc) and it's nil!

What's going on here? What is the correct way to call this transition?

Pelican answered 28/1, 2014 at 20:24 Comment(6)
why did you choose an abandoned gem? By the way transitions have no arguments generallyOvine
The gem was just updated yesterday so I'm not sure what you mean. Also, their README indicates that this is possiblePelican
was on another version, seems like a popular nameOvine
AASM is not abandoned.Nestle
@KyleDecot This seems to be a bug, as it is supposed to work. Could you please open an issue on github.com/aasm/aasm/issues?page=1&state=open ? I'll take care of that today.Nestle
@Ovine Why do you think, the gem has been abandoned?Nestle
C
6

Look aasm docs in section callbacks.

...
  aasm column: :state do
    state :pending_approval, initial: true
    state :active
    state :pending_removal

    after_all_transition :log_all_events

    event :accept_approval, after: :log_approval do
      transitions from: :pending_approval, to: :active
    end
  end
  ...
  del log_all_events(user)
    logger.debug "aasm #{aasm.current_event} from #{user}"
  end

  def log_approval(user)
    logger.debug "aasm log_aproove from #{user}"
  end

You can call events with needed params:

  @post.accept_approval! current_user
Cantus answered 1/2, 2016 at 13:38 Comment(0)
L
3

It works in the current version (4.3.0):

event :finish do
  before do |user|
    # do something with user
  end

  transitions from: :active, to: :finished
end
Lukin answered 14/9, 2015 at 8:12 Comment(1)
Do you call this with post.finish(user)?Cyclamen
R
1
event :accept_approval do
  transitions from: :pending_approval, to: :active
end

post.accept_approval!{post.set_approvaler(current_user)}

block to bang method will be call after transition success, if any activerecord operation, it will be wrap into transition transaction, your can require a lock to prevent concurrency problem with option requires_lock: true.

Reserve answered 12/10, 2017 at 10:16 Comment(0)
Q
1

Move :after to the transitions sections, such that:

event :accept_approval do
  transitions from: :pending_approval, 
    to: :active,
    :after => Proc.new { |user| binding.pry }
end

Then call it as @post.accept_approval!(current_user)

Quieten answered 13/10, 2022 at 16:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.