Skip to content

Instantly share code, notes, and snippets.

@Matt-Yorkley
Last active March 13, 2024 15:54
Show Gist options
  • Save Matt-Yorkley/3a523be8597f20173ba91a872250e69d to your computer and use it in GitHub Desktop.
Save Matt-Yorkley/3a523be8597f20173ba91a872250e69d to your computer and use it in GitHub Desktop.
StimulusReflex with Standalone ActionCable server
# cable/config.ru
require_relative "../config/environment"
Rails.application.eager_load!
app = Rack::Builder.new do
use Rack::Session::Redis, redis_server: Rails.application.config.cache_store[1][:url], **Rails.application.config.session_options
map "/" do
run ActionCable.server
end
end
run app
# app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = user_from_session
end
private
def user_from_session
User.find_by(id: user_id)
end
def user_id
connection_session.dig(1, "warden.user.user.key", 0, 0)
end
def connection_session
return {} unless session_id
ActionDispatch::Session::CacheStore.new(Rails.application).find_session(env, Rack::Session::SessionId.new(session_id))
end
def session_id
env["rack.request.cookie_hash"][Rails.application.config.session_options[:key]]
end
end
end
# app/config/environments/development.rb
Rails.application.configure do
...
config.action_cable.mount_path = nil
config.action_cable.url = "http://localhost:28080" # use wss:// in production
end
...
gem "redis-rack"
When you run ActionCable in standalone mode, it's a stripped-down Rack app without all the usual Rails modules and middleware
like ActionDispatch and Rack::Session, so it doesn't load a session object by default, which is needed in StimulusReflex.
This example assumes the use of Redis as session store and devise for authentication.
Passing the user_id in a separate encrypted cookie is no longer necessary (as the suggested in the docs).
Start the standalone server locally with: `bundle exec puma -p 28080 cable/config.ru`
Standalone ActionCable docs here: https://guides.rubyonrails.org/action_cable_overview.html#standalone
The meta tag helper is required: https://guides.rubyonrails.org/action_cable_overview.html#consumer-configuration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment