Carl Markham Carl Markham - 2 months ago 6
Ruby Question

Rails Interactor rollbacks

I am using the interactor gem in my rails project. When one of the interactors within the organizer fails, the rollback method is called. The question is, is there any way this method can be aware of why the interactor failed?

Example:

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

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

Answer

You can just access the context inside rollback method. There is one catch - rollback of the "current" interactor won't be invoked. Take a look at the following code:

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

it produces "error! from Foo" as the response. Bar throws an exception so FooBar organizer goes back to the Foo and calls its rollback method. context is shared so you have access to everything that was set before.