@santiago-rodrigSantiago Andrés Rodríguez Márquez
Full-stack Developer, chess amateur, languages geek.
There are times when one as a Ruby on Rails developer wants to implement a real-time feature, like a chat application, and after digging a bit you find a framework’s feature named ActionCable, sounds new and scary, right? Fear not, I’ll try to explain it as simple as possible so that at the end of this article you’ll feel comfortable with the subject.
Because we are really busy and our only interest is how to implement the real-time features to our Ruby on Rails application I’ll continue with the steps required to set up ActionCable. The following steps assume that you are familiar with Ruby on Rails and you are using a version of it greater than 5.2.
1. In your Gemfile, add the redis gem and run bundle install.
mount ActionCable.server, at: '/cable'
, you guessed it, ‘/cable’ is the default path.
<%= action_cable_meta_tag %>
at the head of your main layout template.
rails g channel messages
on the terminal.
# app/channels/messages_channel.rb class MessagesChannel < ApplicationCable::Channel def subscribed stream_from 'messages' end end
method is a hash that will be serialized as JSON and received at the side of the client.
# app/controllers/messages_controller.rb class MessagesController < ApplicationController def create # ... if message.save ActionCable.server.broadcast( 'messages', body: message.body, author: message.author ) #... end # ... end end
# config/cable.yml production: adapter: redis url: redis://localhost:6478/1 # ...