ActionCable使用流程

简介: 视频地址:http://railscasts-china.com/episodes/action-cable-rails-5rails命令创建新app$ rails new actioncable_app1.

视频地址:http://railscasts-china.com/episodes/action-cable-rails-5

  1. rails命令创建新app
$ rails new actioncable_app

1.1 在Gemfile文件中加入gem ‘jquery-rails’

1.2在app/assets/javascripts/application.js文件中加入启用jquery的注释

//= require jquery
//= require rails-ujs
  1. rails命令创建controller
$ rails generate controller rooms show
  1. 修改config/routes.rb
root to : 'rooms#show'
  1. rails命令创建model message
$ rails generate model message content:string
  1. rails命令db迁移
$ rails db:migrate
  1. 修改app/controllers/rooms_controller.rb
def show
    @messages = Message.all
end
  1. 创建并修改app/views/messages/_message.html.erb
<div class = "message">
    <p><%= message.content %></p>
</div>
  1. rails命令进入console创建新message
$ rails console
> Message.create! content: "Hello world!"
  1. 修改app/views/rooms/show.html.erb
<h1>Chat room</h1>
<div id = "messages">
    <%= render @messages %>
</div>
  1. rails命令创建新channel
$ rails generate channel room speak
  1. 在config/routes.rb中添加actioncable服务端路径
mount ActionCable.server => '/cable'
  1. 打开app/assets/javascripts/cable.coffee中的@App
@App ||={}
App.cable = ActionCable.createConsumer()
  1. 修改app/asserts/javascripts/channels/room.coffee
speak: (message) ->
@perform 'speak', message: message
  1. 修改app/channels/room_channel.rb中的subscribed函数及speak函数
class RoomChannel < ApplicationCable::Channel
    def subscribed
        stream_from "room_channel"
    end

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">unsubscribed</span></span>
<span class="hljs-keyword">end</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">speak</span><span class="hljs-params">(data)</span></span>
    ActionCable.server.broadcast <span class="hljs-string">'room_channel'</span>, <span class="hljs-symbol">message:</span> data[<span class="hljs-string">'message'</span>]
<span class="hljs-keyword">end</span>

end


  1. 修改app/asserts/javascripts/channels/room.coffee中的received方法

received: (data) -> 
alert data['message']

这时打开调试服务器测试,会跳出js的alert动作

  1. 在app/views/rooms/show.html.erb中添加输入框,对应的数据传给room_speaker

<h1>Chat room</h1>

<div id=“messages”>
<%= render @messages %>
</div>

<form>
<lable>Say something:</lable><br>
<input type=“text” data-behavior=“room_speaker”>
</form>


  1. 在app/assets/javascripts/channels/room.coffee中添加js获取客户端输入,写在speak后面

App.room = App.cable.subscriptions.create “RoomChannel”, 
connected: ->
# Called when the subscription is ready for use on the server

disconnected: ->
# Called when the subscription has been terminated by the server

received: (data) ->
alert data[‘message’]

speak: (message) ->
@perform ‘speak’, message: message

$(document).on ‘keypress’, ‘[data-behavior~=room_speaker]’, (event) ->
if event.keyCode is 13 # return = send
App.room.speak event.target.value
event.target.value =
event.preventDefault()


  1. 修改app/channels/room_channel.rb中的speak函数,把获取的message存到数据库,把广播的功能移出到后续的job

def speak(data) 
Message.create! content: data['message']
end

  1. 修改app/models/message.rb,添加after_create_commit方法,让消息入库后传给job广播

class Message < ApplicationRecord 
after_create_commit { MessageBroadcastJob.perform_later self }
end

  1. rails命令创建新的job文件用来广播收到的消息

$ rails generate job MessageBroadcast

  1. 修改app/jobs/message_broadcast_job.rb文件

class MessageBroadcastJob < ApplicationJob 
queue_as :default

def perform(message)
ActionCable.server.broadcast ‘room_channel’, message: render_message(message)
end

private
def render_message(message)
ApplicationController.renderer.render(partial: ‘messages/message’, locals: { message: message })
end

end


  1. 修改app/assets/javascripts/channels/room.coffee中的received方法

received: (data) -> 
$('#messages').append data['message']

  1. 修改app/views/messages/_message.html.erb 添加cache

<% cache message do %> 
<div class="message">
<p><%=
message.content %></p>
</div>
<%
end %>

目录
相关文章
|
C语言
C语言初阶⑧(结构体)知识点和笔试题
C语言初阶⑧(结构体)知识点和笔试题
444 0
|
存储 弹性计算 Linux
阿里云服务器试用与购买参考:试用与购买流程及相关规则和注意事项
阿里云服务器购买与试用全指南,阿里云每年都会推出针对新用户的免费试用活动,帮助用户低成本体验云服务的强大功能。本文将为大家解析阿里云服务器的购买与试用流程,包括注册认证、领取免费额度、选择实例配置全流程,帮助新手用户快速上手,避免操作误区。
|
8月前
|
缓存 运维 监控
高并发系统卡顿排查:全链路压测平台对比与瓶颈定位指南
文章聚焦高并发系统卡顿排查,指出全链路压测是定位性能瓶颈主流方案。介绍主流全链路压测平台分SaaS化与私有化两类,阐述其特点、适用场景及优劣势。还说明全链路压测核心技术链路、瓶颈定位关键,给出企业落地最佳实践与常见问题解答,助力企业解决高并发难题。
|
人工智能 IDE 搜索推荐
惊!GitHub Copilot或将颠覆传统编程,程序员即将失业?
GitHub Copilot引爆编程界!这个AI编程神器将彻底改变你的编程生涯!
915 22
惊!GitHub Copilot或将颠覆传统编程,程序员即将失业?
|
存储 芯片 内存技术
存储器的分类
存储器的分类
1790 1
|
弹性计算 Ubuntu Shell
用1C1G ECS搭建《阿里云大模型高级工程师ACP认证》学习环境
阿里云推出了《[阿里云大模型高级工程师ACP认证》,配套的学习资料较系统性的梳理了提示词、RAG、Agent插件、微调等系列LLM相关知识。推荐大家学习。 该学习课程需要搭建学习环境,可以直接在ECS上构建该环境即可,所需的资源很少,1C1G20G系统盘最低配置即可,本文介绍了详细搭建过程。
|
存储 关系型数据库 算法框架/工具
Ceph 架构以及部署
Ceph 架构以及部署
951 26
|
数据采集 存储 JSON
从零到一构建网络爬虫帝国:HTTP协议+Python requests库深度解析
在网络数据的海洋中,网络爬虫遵循HTTP协议,穿梭于互联网各处,收集宝贵信息。本文将从零开始,使用Python的requests库,深入解析HTTP协议,助你构建自己的网络爬虫帝国。首先介绍HTTP协议基础,包括请求与响应结构;然后详细介绍requests库的安装与使用,演示如何发送GET和POST请求并处理响应;最后概述爬虫构建流程及挑战,帮助你逐步掌握核心技术,畅游数据海洋。
506 3
|
SQL 消息中间件 关系型数据库
实时计算 Flink版产品使用合集之用tidb连接器flink-connector-tidb-cdc-2.4.1.jar遇到从已存在的ck启动无效问题,启动后仍然从头开始读取数据
实时计算Flink版作为一种强大的流处理和批处理统一的计算框架,广泛应用于各种需要实时数据处理和分析的场景。实时计算Flink版通常结合SQL接口、DataStream API、以及与上下游数据源和存储系统的丰富连接器,提供了一套全面的解决方案,以应对各种实时计算需求。其低延迟、高吞吐、容错性强的特点,使其成为众多企业和组织实时数据处理首选的技术平台。以下是实时计算Flink版的一些典型使用合集。
618 1
|
存储 弹性计算 固态存储
阿里云服务器租用费用1t空间多少钱?全面解析
阿里云服务器租用费用1t空间多少钱?1T空间如果是系统盘SSD云盘价格是3686元一年、ESSD云盘1t空间是5222元一年,ESSD Entry云盘1024G存储空间价格是2580元一年。阿里云百科整理几款不同的云盘1t空间价格