Rails Interactor回滚

时间:2016-09-19 17:05:03

标签: ruby-on-rails ruby

我在rails项目中使用interactor gem。当组织器中的一个交互器失败时,将调用回滚方法。问题是,这种方法有什么办法可以知道交互者失败的原因吗?

示例:

def call
  context.fail! error: 'Some error'
end

def rollback
  # I want to access 'Some error' here
end

1 个答案:

答案 0 :(得分:0)

您只需访问contextrollback方法即可。有一个问题 - “当前”交互器的rollback将不会被调用。看看下面的代码:

require "interactor"

class Foo
  include Interactor

  def call
  end

  def rollback
    p "#{context.error} from Foo"
  end
end

class Bar
  include Interactor

  def call
    context.fail!(error: "error!")
  end

  def rollback
    p "#{context.error} from Bar"
  end
end

class FooBar
  include Interactor::Organizer

  organize Foo, Bar
end

FooBar.call

它生成"error! from Foo"作为响应。 Bar会引发异常,因此FooBar组织者会返回Foo并调用其rollback方法。 context已共享,因此您可以访问之前设置的所有内容。