Rails 5, ActionCable, and Heroku

Jeremy Vermast
2 min readFeb 23, 2017

Recently, I’ve been working on implementing a multiplayer version of the Game of Life, using Rails and Websockets with ActionCable. When wanting to push the app online with Heroku, I realised i could not find any clear and complete step by step to make that work. So, here we go :

Let’s say we made the classic chat app.

First of all, we have to create our middleware :

/app/middleware/chat_action_cable.rbclass 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

then, we need to set the config for production :

/config/environments/production.rb

config.middleware.use ChatActionCable
config.web_socket_server_url = "wss://your-heroku-app.herokuapp.com/"

Now, we need to install the redis plugin on heroku (that should already be included) :

heroku plugins:install heroku-redis (just in case)

Lets spin a new redis instance on heroku :

heroku addons:create heroku-redis:hobby-dev -a young-home-19338
(replace young-home-19338 with your instance name)

Instantiating a redis dyno, will create a REDIS_URL environment variable that we can grab :

heroku config | grep REDIS

For our last step, we will set the config for ActionCable :

/config/cable.ymldevelopment: &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

We need to change the :url, :host, :port and :password.

We got the :url before by checking your REDIS_URL variable.

The :host is everything between @ and :, the :port is the number after the :, and we can get the password like this :

heroku run rails c
uri = URI.parse(<your redis URL>)
uri.password

And that should be good to go !

Don’t hesitate to leave a comment if you have any remark or question.

Some resources that helped me :

Thanks for Reading, hope it helped you !

--

--