collectiveidea / interactor

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

recommended way to abort on success #190

Open ghost opened 4 years ago

ghost commented 4 years ago

I have a set of organizers... The first one is called CheckCache the last one is called WriteCache If CheckCache finds the result that was set from the last call in my Organizer pipeline, I want to abort and just set the cached value on the context.

I don't see any obvious way to tell the Interactor that processing is completed other than to state that it failed which in this case isn't true, it's simply that one of the organizers has found the data needed in the cache that would normally require calling out to another service in the follow up organizers.

Thanks for any advice.

mikebaldry commented 4 years ago

I came here also looking for a fix for this case, I ended up implementing it in the organiser like:

around do |interactor|
  return if can_exit_early?
  interactor.call
end

It's ok for my case, but won't work or will be complicated if you still need some stuff from the context set up or do a few of the interactors then decide then we can exit early successfully

It's definitely a useful feature to be able to stop an interactor early and still be successful.

mikebaldry commented 4 years ago

Thinking about it, if we were to extend Interactor::Context with:

class Success < StandardError; end
def success!(context = {})
  context.each { |key, value| self[key.to_sym] = value }
  raise Success
end

then maybe you could do:

around do |interactor|
  begin
    interactor.call
  rescue Success
    nil
  end
end

or similar and the context will be left as it is, but it's not failed..

kevin-glare commented 3 years ago
module InteractorPatch
  class Success < StandardError; end

  Interactor::Context.class_eval do
    def success!(context = {})
      context.each { |key, value| self[key.to_sym] = value }
      raise Success
    end
  end

  def run!
    super
  rescue Success
  end
end