Last Updated: December 12, 2016
·
965
· tilsammans

Interactors and background workers together

At Space Babies, we love using Interactor to make our controllers much more modular. We also love Sidekiq to perform tasks in the background. You can't use these two techniques together directly, but it's close. Here is how we do it.

This example is to lookup ("reverse-geocode") address from latitude and longitude.

require 'interactor'
require 'sidekiq'
require 'geocode'

# If the photo has lat/lng, lookup the location with a reverse geocode service.
# this is the interactor, called from the controller, which lives in app/interactors
class Photo::Geocode
  include Interactor

  def perform
    Worker.perform_async(photo.id) if photo.has_location?
  end

  # Inner class to lookup the address asynchronously.
  # usually you would put it in app/workers, but we have it inline to keep all code in one place.
  class Worker
    include Sidekiq::Worker

    def perform(photo_id)
      photo = Photo.find photo_id
      photo.update_attribute :location, Geocoder.address("#{photo.latitude},#{photo.longitude}")
    end
  end

end

2 Responses
Add your response

And there I was looking for useful information about debugging my Worker failing within my Interactor and I run into you... there is a god...

over 1 year ago ·

And she is a DJ?

over 1 year ago ·