Skip to content

Instantly share code, notes, and snippets.

@palkan
Last active February 26, 2021 18:26
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save palkan/68c47a96fd06feef1ab2976fc0b2614b 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_current_tenant { super }
end
# The same override for AnyCable, which uses a different method though
def handle_channel_command(*)
using_current_tenant { super }
end
# For #unsubscribed and #disconnect callbacks
def handle_close
using_current_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