ActionCable - Part 1 - Configuration and Basics

#37 ActionCable - Part 1 - Configuration and Basics
7/10/2016

Summary

A walkthrough on configuring ActionCable with Rails 5. Learn how to configure your mount points and the basics of using ActionCable with your Rails application.
6
rails view websockets render

Summary

consolebrew install redis
brew services start redis
development.rbconfig.action_cable.mount_path = '/websocketier'
application.html.erb   <%= action_cable_meta_tag %>
   <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
cable.js//= require action_cable
//= require_self
//= require_tree ./channels

(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer($('meta[name=action-cable-url]').attr('content'));

}).call(this);
consolerails g channel chat
app/channels/chat_channel.rbclass ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chat"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end
messages_controller.rb  def create
    message = Message.create(params[:message].permit!)
    # ActionCable.server.broadcast "chat", { 
    #   message: MessagesController.render(
    #     partial: 'message', 
    #     locals: { message: message }
    #   ).squish 
    # }
  end
message.rbclass Message < ApplicationRecord
  # after_create_commit { 
  #   ActionCable.server.broadcast "chat", { 
  #     message: MessagesController.render(
  #       partial: 'message', 
  #       locals: { message: message }
  #     ).squish 
  #   }
  # }
  
  after_create_commit { MessageBroadcastJob.perform_later(self) }
end
consolerails g job message_broadcast
message_broadcast_job.rbclass MessageBroadcastJob < ApplicationJob
  queue_as :default

  def perform(message)
    ActionCable.server.broadcast "chat", { message: render_message(message) }
  end

  private

  def render_message(message)
    MessagesController.render(partial: 'message', locals: {message: message}).squish
  end
end
app/assets/javascripts/channels/chat.jsApp.chat = App.cable.subscriptions.create("ChatChannel", {
  connected: function() {
    // Called when the subscription is ready for use on the server
  },

  disconnected: function() {
    // Called when the subscription has been terminated by the server
  },

  received: function(data) {
    // Called when there's incoming data on the websocket for this channel
    $('.messages').prepend(data['message']);
  },
});
635114?v=3&s=64
kobaltz said 9 months ago:

Keep in mind that if you are using ActionCable on production, it does not currently work with Apache + Passenger. Instead use Nginx + Passenger.

https://www.phusionpassenger.com/library/config/apache/action_cable_integration/

Login to Comment