回调后 AASM 中的产量项目

Yield items in AASM after callback

你能在 :after 回调中生成项目吗? 当我执行下面的代码时出现 LocalJumpException

require 'aasm'
class TestClass
  include AASM
  aasm do
    state :created, initial: true
    state :running
    event :run do
      transitions from: :created,
      to: :running,
      after: proc { yield 1 }
    end
  end
end
TestClass.new.run! { |v| puts v }

开箱即用是不可能的,因为 aasm 会丢弃传递给事件调用的代码块,但是嘿,它是 ruby。

require 'aasm'
class TestClass
  include AASM
  aasm do
    state :created, initial: true
    state :running
    event :run do
      transitions from: :created,
      to: :running,
      after: -> { @λ_run.call(1) if @λ_run } # invoke the code block if was passed
    end
  end
end
TestClass.prepend(Module.new do
  def run!(*args, &λ)
    @λ_run = λ # store the code block passed to the method
    super
  end
end)
TestClass.new.run! { |v| puts v.inspect }

通过一些元编程应该很容易扩展到所有已定义的事件处理程序。