Rails controllers have callbacks that can be useful when we want to execute a particular piece of code before or after other methods have been invoked. However, there is no Rails built-in after_response_sent callback that could be used to invoke a method after we have rendered the response to the user, either via an HTML or JSON response.
More specifically, we may assume that you have a particular scenario in which you need to do a lot of database updates after a method of a controller has been called. You do not want to perform this using a background job, as it may get delayed and you may need to get the method invoked immediately.
There are workarounds that help you do that. One of them is creating new threads by controllers’ methods. This way, the method will return the response back to the user, and at the same time you have the ability to asynchronously invoke another thread aside.
Spawnling is a really helpful Ruby gem in this regard. It is really simple to install and use. We will not go into the details on how to install it, as it can be found on its Github page. We will simply mention a short example for demonstration purposes.
Let’s say that you have an update method after which you want to do a lot of database insertions. You want to return a response, but you do not want to delay the response back to the user.
Here comes Spawnling. It makes this worry go away:
def update
<span style="font-weight: 400;"> @user.save </span>
<span style="font-weight: 400;"> update_all_user_relations</span>
<span style="font-weight: 400;">end</span>
def update_all_user_relations
<span style="font-weight: 400;">Spawnling.new do</span>
<span style="font-weight: 400;"> #long-running sections</span>
<span style="font-weight: 400;"> end </span>
<span style="font-weight: 400;"> end</span>
<span style="font-weight: 400;">end</span>
It also comes with a few options that you can use, for example like nice which helps you prioritize the threads that you want.
I hope you find this gem helpful.