interactor icon indicating copy to clipboard operation
interactor copied to clipboard

Added ensure

Open ryanfox1985 opened this issue 3 years ago • 6 comments

  • Added ensure interactors.
  • Missing call! method.
  • Added _current_interactor_class in the context.

ryanfox1985 avatar May 16 '22 12:05 ryanfox1985

I don't why but the CI is not triggered...

ryanfox1985 avatar May 16 '22 12:05 ryanfox1985

You can achieve the same behaviour using around-hook and regular ensure.

Example with exxception:

class Test
  include Interactor

  around do |interactor|
    interactor.call
  ensure
    puts "inside around/ensure"
  end

  def call
    puts 'Inside #call. Before excepton.'
    raise "Something went wrong"
    puts 'Inside #call. After exception.'
  end
end

Output:

> Test.call
Inside #call. Before excepton.
inside around/ensure
RuntimeError: Something went wrong

Example with context.fail!

class Test
  include Interactor

  around do |interactor|
    interactor.call
  ensure
    puts "inside around/ensure"
  end

  def call
    puts 'Inside #call. Before excepton.'
    context.fail!(error: "Something went wrong")
    puts 'Inside #call. After exception.'
  end
end

Output:

> Test.call
Inside #call. Before excepton.
inside around/ensure
=> #<Interactor::Context error="Something went wrong">

mainameiz avatar Mar 17 '24 08:03 mainameiz

The beauty of this gem is in its simplicity. It allows you to make almost everything you want on top of it. E.g. you want to track _current_interactor_class . Not everbody want this feature. But you don't need to wait for the gem maintainer to add this feature into the gem. You can do it yourself just for your project:

module TrackCurrentInteractorClass
  extend ActiveSupport::Concern

  included do
    before do
      context._current_interactor_class = self
    end
  end
end

class Test
  include Interactor
  include TrackCurrentInteractorClass

  def call
    puts "Interactor: #{context._current_interactor_class}"
  end
end

Output:

> Test.call
Interactor: #<Test:0x000055779a9dc788>
=> #<Interactor::Context _current_interactor_class=#<Test:0x000055779a9dc788 @context=#<Interactor::Context ...>>>

mainameiz avatar Mar 17 '24 08:03 mainameiz

You can achieve the same behaviour using around-hook and regular ensure.

This is a great example. Maybe this PR can be updated to simply add that example to the README? I needed this "ensure" behavior and was disappointed it wasn't in the "hooks" section of the README.

m1foley avatar Aug 13 '24 19:08 m1foley

@mainameiz sorry for the late response, I think your opinion is subjective. At the library point of view, you have documentation, tests and make easier the integrations (provided by community) then if you move this responsibility to the consumers each consumer needs to implement their own implementation and tests (redundant code).

ryanfox1985 avatar Aug 22 '24 01:08 ryanfox1985