collectiveidea / interactor

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

Atomically call all the interactors in an organizer #156

Closed frankliu81 closed 6 years ago

frankliu81 commented 6 years ago

The interactors in an organizer are sometime used for things related to object creations. After an object is created, we would like to create the associated child objects. What we have found is that this is not happening atomically, then we may have save the object, without the associated child objects created if something happen in between (ie. like a database downtime).

This seems like a common enough feature to have all the interactors in an organizer be called atomically. Would it be a useful option to add to the gem?

Currently, I have to do something one-off for each organizer liks this:

module MyObjects
  class Create
    include Interactor::Organizer

    organize \
      MyObjects::Save,
      MyObjects::SetupAssociations

    def self.call_atomically(context = {})
      # call all the interactors in the Create organizer together atomically
      ActiveRecord::Base.transaction do
        call(context)
      end
    end
  end
end
frankliu81 commented 6 years ago

It turns out we have a module like that in our platform, just have to include TransactionalOrganizer instead.

module TransactionalOrganizer
  extend ActiveSupport::Concern

  included do
    include Interactor::Organizer

    around do |organizer|
      ActiveRecord::Base.transaction { organizer.call }
    end
  end
end