Skip to main content

Best practices for manipulation/working with data from model after creation

Rails • Asked by eelcoj

Consider the situation where a model is created to which the data needs to manipulated/worked with right after creation. For instance find (*match) a certain string from a long string, convert (parts of) the long string to PDF, upload some attachments to S3, etc.

The most obvious way to me, would be to put all this separate model's methods in a background worker.

But I was also thinking of extracting these methods into some rake task (which can then also be moved to a background queue).

Basically just curious if there are other ways to go about this. Maybe I am overthinking, but who knows (at this time of the year… ;)).

Hey Jack,

This would be a good place to write a Ruby class that handles the processing, and then you can call that class and pass in the objects you need from background workers or rake tasks. Since the class would be agnostic, you can use the background worker or rake task to feed in the inputs like the model you need to process and the work can be done in either spot with the same code. Having a rake task is easy for testing, and then background jobs are important for production tasks, so a Ruby class would let you do that nicely.

Something like this:

# Your processing class
class ProcessWhatever
  def perform(model_id)
      model = Model.find(model_id)

        # do your work here
# Your background worker can call it
class ProcessJob < ApplicationJob
  def perform(model_id)
# Rake task
task :process_whatever do

Just to +1 what Chris said - this is the perfect scenario for service objects! If you haven't already, check out his video on PORO's -

There are a ton of articles on the interwebz (keywords: ruby poro or ruby service objects) that I would strongly suggest reading since the whole idea is more about organization of code more so than core functionality once you understand how to use them.

Good luck! :)

Thanks both Chris and Jacob. Really helpful. 🙌 I got some viewing and reading to do.

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.