Since there is not much up-to-date information with latest versions of Rails and Pusher, how can I implement Pusher in my Rails app to get realtime chat between users? The Pusher documentation shows how to do this with Sinatra, but there isn't anything specific to Rails...
问题:
回答1:
Create an initializer file
app/config/initializers/pusher.rb
require 'pusher'
Pusher.url = 'your-pusher-url'
Pusher.logger = Rails.logger
In your controller, lets assume this is for chat messages:
app/controllers/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
Authorization
app/controllers/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:
routes.rb
YourApp::Application.routes.draw do
resources :messages
post '/pusher/auth' => 'pusher#auth'
end
Somewhere in your coffescript, most likely in application.coffee, this assumes you have the pusher cdn js file in your application.html.haml and jquery installed.
$->
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
notice that you should added meta tags to your head so you easily grab csrf token, user_id and pusher key. You of course need csrf token to stop spoofing.
In your 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 assumes you are using some kind of authenication. csrf_meta_tag is a built in rails helper. Notice that I put my js on the last line of body. do not place your js in the head.