MailChimp and Active Job on Rails 4 – adding users to your mailing list in the background

When a user registers for your app, you might want to add them to your mailing list.  This normally takes a few seconds, as your app has to communicate with the mailing list provider. Still, the user should not have to wait, so we’ll immediately bring the user to the next page while subscribing them to the mailing list in the background.

Rails 4.2 offers Active Job, an easy way to define background jobs.

This example uses MailChimp for the mailing list and Devise for authentication, but Active Job does not depend on either. The example uses gibbon gem to communicate with MailChimp, and dotenv to store the MailChimp API key and list ID as environment variables on dev.

First, add a job for adding a user to the mailing list.

This generates a new job:

Next, customize the job to accept a user parameter, and subscribe that user to the MailChimp list.

Finally, in our user class, run the job after a new user is created:

Notice that we are passing the newly created user to the job, which then subscribes them to the mailing list.

Active Job is smart enough to realize that we don’t currently have a background job backend, so it performs the action right away, thus making the user wait. Once you add a backend, let Active Job know and you’ll have yourself a true background job. There are many backends to choose from, including Delayed Job, Sidekiq, and Resque,

Performing tasks in the background and eliminating delays for users has never been easier, thanks to Rails 4.2 and Active Job. brings Rails job offers to you. Free for candidates. Salaries from $75,000 to $250,000. Sign up now!

4 thoughts on “MailChimp and Active Job on Rails 4 – adding users to your mailing list in the background”

Leave a Reply