Section 2 is to be had right here.
Supply code is to be had right here.

Let me will let you!
Howdy, I’m Anatoly, founding father of this weblog. I would really like that can assist you! I’ve 6+ years revel in in Internet Construction and IT Management. We could paintings in combination in your mission! Depart me your e-mail and I can agenda a FREE Session!
Thanks for proceeding to practice this instructional. Should you stumble in this put up and don’t know what taking place, please take a look at Section 1 and Section 2 that covers fundamental setup and styling. Additionally please take a look at Are living Demo for the general end result. Should you like to leap immediately into the code, here’s the supply code for all 3 portions.
On this phase we will be able to hook are living streaming to our energetic notification heart!
Say hi to ActionCable!
ActionCable permits you to open a streaming channel and flow your occasions are living, with out want to refresh!
We could test it out!
ActionCable Magic
To create ActionCable flow first we will be able to want to create a brand new channel. We could scaffold it. Move on your terminal, navigate to notificator folder and run the next command:
rails g channel notifications
This will likely create JavaScript and Ruby Channel for our notificator.
We could allow streaming from notification_channel:
notificator/app/channels/notifications_channel.rb
# Make sure to restart your server whilst you alter this report. Motion Cable runs in a loop that doesn't strengthen auto reloading. elegance NotificationsChannel < ApplicationCable::Channel def subscribed stream_from "notification_channel" finish def unsubscribed # Any cleanup wanted when channel is unsubscribed finish finish
As you could see I’ve uncommented stream_form and gave it a reputation “notification_channel”. We will be able to use this identifier to grasp the place to broadcast our adjustments.
Additionally since we’re right here, we want to specify which direction ActionCable can mount to.
We could cross to routes and upload ActionCable mount direction:
notificator/config/routes.rb
Rails.utility.routes.draw do root to: 'notifications#index' assets :messages # For main points at the DSL to be had inside of this report, see # Websockets resemble this URL mount ActionCable.server => '/cable' finish
New piece is mount ActionCable.server. This specifies that ActionCable will mount to /cable.
We’re nearly completed with the setup!
Restart your rails server, refresh your browser. You could see following error on your rails logs:
Request starting place no longer allowed:
I’ve create separate put up the right way to get to the bottom of it ,however to your comfort, I can repeat it right here.
Move to notificator/config/environments/construction.rb and upload following line:
config.action_cable.allowed_request_origins = ['']
Be aware: You’ll be able to additionally put separated by means of coma if you wish to have
Restart your server, refresh the web page, and now you will have to see one thing like this:
Effectively upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Improve, HTTP_UPGRADE: websocket) NotificationsChannel is transmitting the subscription affirmation
Which means that channel is operating correctly! Excellent task on that!
Our subsequent step is to make our counter to replace are living. We additionally wish to have just a little of animation when counter quantity changel. For this we will be able to use JQuery transition. Please obtain library from right here . And put it into:
notificator/supplier/property/javascripts/jquery.transit.min.js
To make this report to be had in every single place, shall we additionally come with it in utility.js:
notificator/app/property/javascripts/utility.js
// This can be a manifest report that'll be compiled into utility.js, which is able to come with the entire recordsdata // indexed under. // // Any JavaScript/Espresso report inside of this listing, lib/property/javascripts, supplier/property/javascripts, // or any plugin's supplier/property/javascripts listing may also be referenced right here the usage of a relative trail. // // It is not beneficial so as to add code at once right here, however in case you do, it's going to seem on the backside of the // compiled report. JavaScript code on this report will have to be added after the final require_* observation. // // Learn Sprockets README ( for main points // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require jquery.transit.min //= require_tree .
As you spot, I’ve added this library proper prior to require_tree. We could refresh web page and ensure not anything blew up 🙂
Since we’ve transitions, shall we use them!
We could cross to our channel/notifications.espresso, and upload customized behaviour for when our channel receives new information.
notificator/app/property/javascripts/channels/notifications.espresso
App.notifications = App.cable.subscriptions.create "NotificationsChannel", hooked up: -> # Known as when the subscription is able to be used at the server disconnected: -> # Known as when the subscription has been terminated by means of the server gained: (information) -> # Known as when there is incoming information at the websocket for this channel this.update_counter(information.counter) update_counter: (counter) -> $counter = $('#notification-counter') val = parseInt $counter.textual content() val++ $counter .css({opacity: 0}) .textual content(val) .css({best: '-10px'}) .transition({best: '-2px', opacity: 1})
We have now added update_counter serve as, this is caused every time flow receives information. update_counter purposes adjustments textual content of the counter to a brand new quantity, and does it the usage of transition from the highest.
To make it paintings we want to go new counter price to the flow.
Since tournament streaming is an excessively pricey activity, we don’t wish to do it in foreground. We could create background task that can care for it. Move on your notificator app in terminal and run:
rails generate task NotificationBroadcast
This will likely create app/jobs/notification_broadcast_job.rb . We could cross there aand by means of this task broadcast our new counter price when new notification is created.
notificator/app/jobs/notification_broadcast_job.rb
elegance NotificationBroadcastJob < ApplicationJob queue_as :default def carry out(counter) ActionCable.server.broadcast 'notification_channel', counter: render_counter(counter) finish non-public def render_counter(counter) ApplicationController.renderer.render(partial: 'notifications/counter', locals: { counter: counter }) finish finish
We did right here 2 issues:
First we handed counter to accomplish task motion, which declares this new price to ActionCable notification_channel that we’ve got created previous.
2d we made it broadcast entire partial with up to date counter price.
Highest!
Final piece left prior to we will be able to see our counter updating are living. I promise!
To make it paintings we want to name this task and go it counter price. We additionally wish to do it each and every time new notification is created.
We could put task advent into after_create_commit hook of Notification.
notificator/app/fashions/notification.rb
elegance Notification < ApplicationRecord after_create_commit { NotificationBroadcastJob.perform_later(Notification.depend)} finish
This after_create_commit hook creates not on time task and passes notifications depend to it. Very simple.
Sufficient speaking, shall we see it. Restart your server. Open 2 browser home windows facet by means of facet.
First window: /messages/new
2d window: /
Now create message within the first window, and have a look at counter in the second one window.
Growth! Magic 🙂
Beautiful wonderful, hugh ?
The one piece that I wish to upload right here, is to append new remark to the modal as neatly.
This will likely permit us to have a look at the entire waft as soon as once more.
We could make our notifications extra descriptive. We could lead them to display precise Message.
notificator/app/fashions/message.rb
elegance Message < ApplicationRecord after_create_commit { notify } non-public def notify Notification.create(tournament: "New Notification (#{self.frame})") finish finish
In line 7 this time we’re passing “self.frame”, this manner we will be able to ready to peer message frame in our modal.
Subsequent shall we replace our broadcasting task to simply accept and render notification partial:
notificator/app/jobs/notification_broadcast_job.rb
elegance NotificationBroadcastJob < ApplicationJob queue_as :default def carry out(counter,notification) ActionCable.server.broadcast 'notification_channel', counter: render_counter(counter), notification: render_notification(notification) finish non-public def render_counter(counter) ApplicationController.renderer.render(partial: 'notifications/counter', locals: { counter: counter }) finish def render_notification(notification) ApplicationController.renderer.render(partial: 'notifications/notification', locals: { notification: notification }) finish finish
We’re passing notification to accomplish, from there we’re passing it to ActionCable however first we render it as partial. (Identical as counter prior to)
For this to paintings we’d like our Notification to be handed to our task. We could do it by means of updating hook in Notification and passing self:
notificator/app/fashions/notification.rb
elegance Notification < ApplicationRecord after_create_commit { NotificationBroadcastJob.perform_later(Notification.depend,self)} finish
Cool! Final piece, we want to append our notification to notifications record by means of JavaScript. Have in mind how we up to date counter ? We could do the similar with notification:
notificator/app/property/javascripts/channels/notifications.espresso
App.notifications = App.cable.subscriptions.create "NotificationsChannel", hooked up: -> # Known as when the subscription is able to be used at the server disconnected: -> # Known as when the subscription has been terminated by means of the server gained: (information) -> # Known as when there is incoming information at the websocket for this channel $('#notificationList').prepend "#{information.notification}" this.update_counter(information.counter) update_counter: (counter) -> $counter = $('#notification-counter') val = parseInt $counter.textual content() val++ $counter .css({opacity: 0}) .textual content(val) .css({best: '-10px'}) .transition({best: '-2px', opacity: 1})
One line alternate: in gained serve as we’re prepending information.notification .
Thats it. Now shall we check out two window magic another time. Restart your server, refresh your browsers.Open and stay your modal opened in a single browser window, create new message in different browser window:
What you will have to see is how notifications are showing are living in addition to counter price converting.
Congrats! You will have completed it!
Thank for you finishing the educational.
That is it for coding phase. If you’re curious the right way to deploy it to Heroku, please learn Section 4.
Please put up your questions into remark phase.
Should you like what you spot please Subscribe to my weblog. If you wish to have assist along with your mission, please Get In Contact.
Thank you for putting in the Backside of each and every put up plugin by means of Corey Salzano. Touch me if you wish to have customized WordPress plugins or web site design.