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
Written by Joost Baaij
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#