Home > other >  Rails: call same method in after_commit for create, update, delete but do separate things based on c
Rails: call same method in after_commit for create, update, delete but do separate things based on c

Time:12-09

I want to create and delete the user on a 3rd party service based on the below scenarios

  1. create user on 3rd party

    • when user is created in the application
    • marked as active from inactive (i have a column on my User model called is_active)
  2. delete user on 3rd party

    • when user is deleted from the application
    • marked as inactive

looks like I can make use of the after_commit callback, but how do I identify in the after_commit that action is create, update or delete

Any help on this will be helpful.

CodePudding user response:

Don't use a callbacks for this - you are going to regret it. The main problem with callbacks are:

  • No context - you don't actually have any idea whats going on in the app.
  • Its hard to control when the callback actually fires and more importantly when you don't want it to fire (like for example when loading fixtures).
  • It puts to much responsibity on the model.
  • You can't test the callback logic in isolation from creating/updating/destroying the record.

I really can't understate this when you seem to be dealing with a third party API as well. Using an implicit mechanizm like callbacks when you're touching the application boundry is a really bad idea. The whole idea of piping everything through a single method is also not sound.

Instead you can use patterns such as service objects to handle the "transformations" of the model.

class UserCreationService
  def initialize(user)
    @user = user
  end

  def perform
    # do something with @user
  end
end


class UserInactivationService
  def initialize(user)
    @user = user
  end

  def perform
    # do something with @user
  end
end

These do a single job and are easy to test and will only fire when you explicitly want them to. ActiveJob is actually an example of this pattern.

  • Related