Using Delayed Job on getting geocords with gmaps4rails
-
13-11-2019 - |
Вопрос
I am looking at using the gem google maps for rails but cant see how I can use delayed_job to get the cords after creating a new record.
Has anyone come across this gem before with using delayed_job
Hope someone can advise.
Решение
Alright, I'm not sure how much you know about Delayed Job, so I'll start there.
Delayed job can utilize any class that responds to '#perform', so the first thing you need is a class for getting the coordinates and storing them in your model.
class GoogleMapsCoordinateService
def perform(record)
coords = Gmaps4rails.geocode(record.address) #This is the method that will actually return a hash of coordinates for each match it finds.
record.update_attributes(:lattitude => coords[0][:lat], :longitude => coords[0][:lng])
end
end
Then you just need to enqueue that job in an after_create hook in the model
class INSERTYOURMODELNAMEHERE < ActiveRecord::Base
after_create :get_coordinates
def get_coordinates
Delayed::Job.enqueue GoogleMapsCoordinateService.new(self)
end
end
So that way, after each record is created, you will queue up the grabbing of the coordinates in the background while keeping your response time snappy.
Не связан с StackOverflow