实现Rails中推聊天(Implementing Pusher chat in Rails)

2019-10-22 07:00发布

由于没有太多向上的最新信息与Rails和推杆的最新版本,我怎么能在我的Rails应用程序执行推杆让用户之间的实时聊天? 推动文档显示了如何西纳特拉做到这一点,但没有具体到Rails的东西...

Answer 1:

创建初始化文件

应用程序/配置/初始化/ pusher.rb

require 'pusher'

Pusher.url    = 'your-pusher-url'
Pusher.logger = Rails.logger

在你的控制器,让我们假设这是聊天消息:

应用程序/控制器/ messages_controller.rb

MessagesController < ApplicationController
  def create
    model = Message.create params_model
    json  = model.to_json
    channel = "private-conversation.#{params[:user_id]}"
    Pusher[channel].trigger 'messages/create', json
  end

  private
    def params_model
      params.require(:message).permit(:id,:body,:user_id)
    end
end

授权

应用程序/控制器/ pusher_controller.rb

class PusherController < ApplicationController
  protect_from_forgery except: :auth_notify
  skip_before_filter :login_required, only: [:auth_notify]
  def auth
    channel    = params[:channel_name]
    socket_id  = params[:socket_id]

    valid = false
    valid = true if channel =~ /private-conversation\.(\d+)/

    if valid
      response = Pusher[channel].authenticate socket_id
      render json: response
    else
      render text: 'Not authorized', status: '403'
    end
  end
end

路线:

的routes.rb

YourApp::Application.routes.draw do
  resources :messages
  post '/pusher/auth'    => 'pusher#auth'
end

在某处,coffescript,最有可能在application.coffee,这里假设你有推动CDN js文件在你application.html.haml和jQuery安装。

$->
    user_id = $('meta[name=user-id]').attr('user_id')
    key     = $('meta[name=pusher-key]').attr('content')
    csrf    = $('meta[name=csrf-token]').attr('content')
    @pusher = new Pusher key,
      auth:
        headers:
          'X-CSRF-Token': csrf
        params:
          user_id: user_id

请注意,你应该加入meta标签到你的头上,所以你很容易抢CSRF令牌,USER_ID和推进的关键。 当然,你需要CSRF令牌来阻止欺骗。

在你application.html.haml

!!! XML
!!! 5
%html
  %head
    = csrf_meta_tag
    = tag :meta, name: 'pusher-key', content: "#{current_user.id}"
    = tag :meta, name: 'pusher-key', content: 'pusher_public_key'
  %body
    = javascript_include_tag '//js.pusher.com/2.2/pusher.min.js'
    = javascript_include_tag :application

CURRENT_USER假定您使用某种authenication的。 csrf_meta_tag是一个内置的轨道帮手。 请注意,我把我的js在身体的最后一道防线。 不要把你的js的头部。



文章来源: Implementing Pusher chat in Rails