我认为网上的例子不完整。
你的中间件应该继承自ActionCable::Connection::WebSocket
class ChatActionCable < ActionCable::Connection::WebSocket
def initialize(app, options={})
@app = app
end
def call(env)
if ::WebSocket::Driver.websocket?(env)
ActionCable.server.call(env)
else
@app.call(env)
end
end
end
对于想了解如何使用 Heroku 设置 ActionCable 的人,这里有一个分步指南:
创建中间件文件:
/app/middleware/chat_action_cable.rb
class ChatActionCable < ActionCable::Connection::WebSocket
def initialize(app, options={})
@app = app
end
def call(env)
if ::WebSocket::Driver.websocket?(env)
ActionCable.server.call(env)
else
@app.call(env)
end
end
end
在配置中设置:
/config/environments/production.rb
config.middleware.use ChatActionCable
config.web_socket_server_url = "wss://your-heroku-app.herokuapp.com/"
在heroku上设置redis插件(应该已经包含了):
heroku plugins:install heroku-redis (in case)
创建一个新的 redis heroku 实例:
heroku addons:create heroku-redis:hobby-dev -a young-home-19338
(replace young-home-19338 with your instance name)
它会设置一个REDIS_URL 环境,你可以使用:
heroku config | grep REDIS
现在,设置 actionCable 的配置:
/config/cable.yml
development: &development
:url: redis://localhost:6379
:host: localhost
:port: 6379
:timeout: 1
:inline: true
test: *development
production: &production
:url: redis://redistogo:192csd9c30ca49585ce9d85daf0fer90@tarpon.redistogo.com:49382
:host: tarpon.redistogo.com
:port: 49382
:password: 349f93483fv9erfv849dfvdfbds9
:inline: true
:timeout: 1
主机在@和:之间
端口在: 之后
密码:
heroku run rails c
uri = URI.parse(<your redis URL>)
uri.password
应该就是这样了。
我参考了这两篇文章:
http://www.thegreatcodeadventure.com/deploying-action-cable-to-heroku/
https://blog.heroku.com/real_time_rails_implementing_websockets_in_rails_5_with_action_cable