Faye WebSockets - Part 1

#22 Faye WebSockets - Part 1
2/23/2016

Summary

Using WebSockets, we are able to create a realtime notification between browsers. Useful for in-app messaging, chats, and more! Learn how to use Faye's Publish and Subscribe methods. I believe that this paves the way for successfully using and learning the upcoming ActionCable.
3
rails websockets realtime messaging notifications 7:07 min

Summary

application.html.erb<%= javascript_include_tag "http://localhost:8080/faye/faye.js" %>
application.js    // CoffeeScript
    // $(document).ready ->
    //   faye = new (Faye.Client)('http://localhost:8080/faye')
    //
    //   faye.subscribe '/about', (data) ->
    //     eval data
    //
    //   $('.subscribe').each ->
    //     faye.subscribe '/' + $(this).data('channel'), (data) ->
    //       eval data
    //     return

    $(document).ready(function() {
      var faye = new Faye.Client("http://localhost:8080/faye");

      faye.subscribe('/about', function(data) { return eval(data)});
      // faye.subscribe('/profile', function(data) { return eval(data)});
      faye.subscribe('/contact', function(data) { return eval(data)});

      $('.subscribe').each( function(){
       faye.subscribe('/' + $(this).data('channel'), function(data) { return eval(data)});
      })
    });
pages_controller.rb    class PagesController < ApplicationController
      include ApplicationHelper
      def about
        message = "toastr.info('#{render_to_string partial: '/pages/hello_world'}')".squish
        # <%= render 'pages/hello_world', f: f %>
        # <%= render 'pages/hello_world', locals: { f: f } %>
    
        broadcast_message '/about', message
      end

      def profile
        message = "toastr.info('Someone has just joined the profile page')"
        broadcast_message '/profile', message
      end

      def contact
        message = "toastr.info('Someone has just joined the contact page')"
        broadcast_message '/contact', message
      end
    end
profile.html.erb<%= content_tag :div, nil, class: 'subscribe', data: { channel: 'profile' } %>
application_helper.rb    module ApplicationHelper
      def broadcast_message(channel, content)
        message = { channel: channel, data: content, ext: {auth_token: 'secret'}}
        uri = URI.parse('http://localhost:8080/faye')
        http = Net::HTTP.new(uri.host, uri.port)
        request = Net::HTTP::Post.new(uri.request_uri)
        request.set_form_data(message: message.to_json)
        return http.request(request)
      end
    end


901101?v=3&s=64
mabel said over 1 year ago:

Super! waiting for part2

635114?v=3&s=64
kobaltz said over 1 year ago:

I hope to get it recorded this weekend.

Login to Comment