Last active
February 26, 2021 18:26
-
-
Save palkan/68c47a96fd06feef1ab2976fc0b2614b to your computer and use it in GitHub Desktop.
Action/AnyCable + Apartment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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