collectiveidea / interactor

Interactor provides a common interface for performing complex user interactions.
MIT License
3.36k stars 212 forks source link

Added ensure #206

Open ryanfox1985 opened 2 years ago

ryanfox1985 commented 2 years ago
ryanfox1985 commented 2 years ago

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

mainameiz commented 8 months ago

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 commented 8 months ago

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 ...>>>
m1foley commented 3 months ago

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.

ryanfox1985 commented 2 months ago

@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).