在Rails中实现Pusher聊天

由于最新版本的Rails和Pusher没有太多最新信息,我如何在我的Rails应用程序中实现Pusher以实现用户之间的实时聊天? Pusher文档显示了如何使用Sinatra执行此操作,但Rails没有任何特定内容……

创建初始化文件

应用程序/配置/初始化/ 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中,这假设你在application.html.haml和jquery中安装了推送cdn js文件。

 $-> 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 

请注意,您应该在头部添加元标记,以便轻松获取csrf标记,user_id和pusher密钥。 你当然需要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假设您正在使用某种身份validation。 csrf_meta_tag是内置的rails helper。 请注意,我把我的js放在身体的最后一行。 不要把你的js放在头上。