视频地址:http://railscasts-china.com/episodes/action-cable-rails-5
视频地址:http://railscasts-china.com/episodes/action-cable-rails-5
$ rails new actioncable_app
1.1 在Gemfile文件中加入gem ‘jquery-rails’
1.2在app/assets/javascripts/application.js文件中加入启用jquery的注释
//= require jquery
//= require rails-ujs
$ rails generate controller rooms show
root to : 'rooms#show'
$ rails generate model message content:string
$ rails db:migrate
def show
@messages = Message.all
end
<div class = "message">
<p><%= message.content %>p>
div>
$ rails console
> Message.create! content: "Hello world!"
<h1>Chat roomh1>
<div id = "messages">
<%= render @messages %>
div>
$ rails generate channel room speak
mount ActionCable.server => '/cable'
@App ||={}
App.cable = ActionCable.createConsumer()
speak: (message) ->
@perform 'speak', message: message
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel"
end
def unsubscribed
end
def speak(data)
ActionCable.server.broadcast 'room_channel', message: data['message']
end
end
received: (data) ->
alert data['message']
这时打开调试服务器测试,会跳出js的alert动作
<h1>Chat roomh1>
<div id=“messages”>
<%= render @messages %>
div>
<form>
<lable>Say something:lable><br>
<input type=“text” data-behavior=“room_speaker”>
form>
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()
def speak(data)
Message.create! content: data['message']
end
class Message < ApplicationRecord
after_create_commit { MessageBroadcastJob.perform_later self }
end
$ rails generate job MessageBroadcast
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
received: (data) ->
$('#messages').append data['message']
<% cache message do %>
<div class="message">
<p><%= message.content %>p>
div>
<% end %>