Using Web Socket for Real Time Push Notifications in Rails

Getting started with websocket in rails pretty simple and quick.

  1. Add Gemfile gem to your Gemfile and run the bundle command.
  2. Run generator: rails g websocket_rails:install.
  3. In your application.js do

application.js

application.js
1
2
3
4
5
var dispatcher = new WebSocketRails('localhost:3000/websocket');
dispatcher.bind('tasks.create_success', function(task) {
  console.log('successfully created ' + task.name);
});
      
  1. In controller from where ever the notification has to be sent
tasks_controller.rb
1
2
3
4
5
6
7
8
9
10
class TasksController < ApplicationController

  def create
      @task = Task.new(content: params[:content])
      if @task.save
          WebsocketRails[:tasks].trigger 'create_success', @task
      end
  end

end

This is it, the minimal setup for using websocket is complete. Every time a task is created, a messages is sent to all over the active websocket connections. I have done console.log. After getting data we can process it any ways we want. Such as :

application.js
1
2
3
4
dispatcher.bind('tasks.create_success', function(task) {
  $('.tasks_list').append('<li>' + task.content + '</li>')
});
      

Comments