rails 5 cable

rails5 beta版已经发布,引入的新特性即为cable,是一个封装过的websocket客户端/服务器端工具,railscasts-china 上有一个dhh的rails5 cable介绍的视频,按部就班地实现了下,感觉rails5非常强大~

1 安装 rails5

gem install rails -v 5.0.0.beta1

2 rails new campfire创建项目

3 创建 room channel

使用命令 rails g channel room 创建 room_channel.rb和rooms.coffee
room_channel.rb

class RoomChannel < ApplicationCable::Channel
  def subscribed
    stream_from "room_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
  
  #处理websocket请求
  def speak(data)
    Message.create! content: data['message']
  end
end

rooms.coffee

App.room = App.cable.subscriptions.create "RoomChannel",
  connected: ->
    
  disconnected: ->
    
  received: (data)->
    $("#messages").append data['message']
  #js 使用websocket发送信息
  speak: (message)->
    @perform 'speak',message:message      

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

message.rb

#貌似不再是AcativeRecord::Base了
class Message < ApplicationRecord
  #使用 job广播
  after_create_commit { MessageBroadcastJob.perform_later self } 
end

message_broad_cast_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

从示例来看通过cable使用websocket是相当方便,rails 5你值得尝试~

示例代码:[https://github.com/secondrocker/campfire]
视频地址:[http://railscasts-china.com/episodes/action-cable-rails-5?autoplay=true]

你可能感兴趣的:(rails 5 cable)