Skip to content

Instantly share code, notes, and snippets.

@matedemorphy
Forked from palkan/connection.rb
Created June 7, 2020 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matedemorphy/497c96de51d813c536c38f1509ae0a49 to your computer and use it in GitHub Desktop.
Save matedemorphy/497c96de51d813c536c38f1509ae0a49 to your computer and use it in GitHub Desktop.
Action/AnyCable + Apartment
module ApplicationCable
class Connection < ActionCable::Base::Connection
# we need to keep tenant information for subsequent messages,
# so let's store it as an identifier
identified_by :tenant
def connect
# assuming you store current tenant in session
self.tenant = request.session[:current_tenant]
reject_unauthorized_connection unless tenant
using_current_tenant do
# set additional identifiers
end
end
# Override to make all channel commands tenant-aware
# There is not middleware-like functionality for Action Cable,
# so we need to patch it
def dispatch_websocket_message(*)
using_tenant { super }
end
# The same override for AnyCable, which uses a different method though
def handle_channel_command(*)
using_tenant { super }
end
private
def using_current_tenant(&block)
Apartment::Tenant.switch(&block)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment