【发布时间】:2026-01-19 03:20:03
【问题描述】:
config/application.rb 文件
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
module Blog
class Application < Rails::Application
config.middleware.insert_before 0, "Rack::Cors", :debug => true, :logger => (-> { Rails.logger }) do
allow do
origins '*'
resource '/cors',
:headers => :any,
:methods => [:post],
:credentials => true,
:max_age => 0
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :options, :head],
:max_age => 0
end
end
end
end
pusher_controller.rb pusher api 用于弹出通知,如 takeofflabs.com 中所述
class PusherController < ApplicationController
def auth
if current_user && params[:channel_name]=="private-user-current-#{current_user_id}"
response = Pusher[params[:channel_name]].authenticate(params[:socket_id])
render :json => response
else
render "not_authorized" , :status =>'403'
end
end
def show
Pusher.app_id = PUSHER_APP_ID
Pusher.key = PUSHER_KEY
Pusher.secret = PUSHER_SECRET
x= render_to_string(:partial => "/views/notifications/notification")
Pusher["private-user-#{@notification.user_id}"].trigger('new-notification',x)
end
end
环境.rb 文件 需要 File.expand_path('../application', FILE)
PUSHER_APP_ID = "101053"
PUSHER_KEY = "89979ad24549eabc3764"
PUSHER_SECRET = "f4c1a6ca70d523e9e72e"
application.html.erb
<html>
<head>
<title>Blog</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
<%= javascript_include_tag "http://js.pusherapp.com/2.2/pusher.min.js" %>
<script>
var pusher = new Pusher("#{PUSHER_KEY}");
var userChannel = pusher.subscribe("private-user-#{current_user.id}");
userChannel.bind('new-notification', function(message) {
$(".notifications_area").html(message);
});
</script>
</head>
<body>
<%if current_user %>
Logged in as: <%= current_user.email if current_user %>
<%else%>
PLEASE LOG IN TO SEE THE ARTICLES
<%end%>
<%= yield %>
</body>
</html>
Rails.application.initialize!
【问题讨论】:
标签: ruby ruby-on-rails-4 ruby-on-rails-4.1 pusher