Clone wiki

asd-2016 / practice12a

Asynchronous Jobs (Sucker Punch)

Add the following Sucker Punch gems to your application's Gemfile:

gem 'sucker_punch', '~> 2.0'

For Rails, you could add an initializer:

# config/initializers/sucker_punch.rb

require 'sucker_punch/async_syntax'

Do not forget to run bundle update.

We are now ready to write the Ruby code to extend the application with support to asynchronous interactions.

The fist step corresponds to adding a Sucker Punch job. Copy the following code snippet into the file app/jobs/bookings_async_job.rb.

class BookingsAsyncJob
  include SuckerPunch::Job
  def perform(message, latitude, longitude)
    Pusher.trigger('bookings', 'async_notification', {:message => message})

Indeed, this is the class on where we will perform the hard work (e.g., calling Google maps geolocation/directions service, interact with the taxi driver, etc.). At the end of all the computation, we would have the result. In that case, we are going to "push" the result via "Pusher" into the channel bookings. The message is associated with an event async_notification (this should be consistent with what we configured in the front-end).

Now, let's connect this worker with the controller. Change the content of the file controllers/bookings_controller.rb with the following snippet.

class BookingsController < ApplicationController
  def create"Your booking has been confirmed", 0, 0) # actual coordinates ?
    render :text => {:message => 'Submitted information is being processed'}.to_json, status: :created

The documentation of sucker_punch can be found at