Using ActionCable to provide updates on background job in your Rails app

rails g channel Notifications
class NotificationsChannel < ApplicationCable::Channel
def subscribed
# stream_from "some_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
class NotificationsChannel < ApplicationCable::Channel
def subscribed
stream_from "notifications:#{current_user.id}"
end
def unsubscribed
stop_all_streams
end
end
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user

def connect
self.current_user = find_verified_user
end

private
def find_verified_user
if current_user = User.find_by(id: cookies.signed[:user_id])
current_user
else
reject_unauthorized_connection
end
end
end
end
App.notifications = App.cable.subscriptions.create("NotificationsChannel", {connected: function() {},disconnected: function() {},received: function() {}});
received: function(data) {
$('#notifications').html(data.html);
}
class BasketWorker
include Sidekiq::Worker
def perform(id, date, token)
user = User.find(id)
ActionCable.server.broadcast "notifications:#{user.id}", {html:
"<div class='alert alert-warning alert-block text-center'>
<i class='fa fa-circle-o-notch fa-spin'></i>
Searching your gmail for receipts now (it might take a minute if there are many).
</div>"
}
Scraper.process_emails(user, date, token) ActionCable.server.broadcast "notifications:#{user.id}", {html:
"<div class='alert alert-success alert-block text-center'>
Search complete!
</div>
}
end
end

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Daniel

Daniel

More from Medium

How to get & build full URLs in Rails

CircleCI Setup For Ruby On Rails Project

Rails Project Reflection — A Ruby on Rails Recipe Manager

Ruby on Rails in a Nutshell