Skip to content

Instantly share code, notes, and snippets.

@ryenski
Last active November 21, 2018 22:44
Show Gist options
  • Save ryenski/a19cb1c06a6b00c467cc220f3facfd07 to your computer and use it in GitHub Desktop.
Save ryenski/a19cb1c06a6b00c467cc220f3facfd07 to your computer and use it in GitHub Desktop.
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :authenticate_user!
include CurrentTenant
end
# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
attribute :tenant, :user, :membership
resets { Time.zone = nil }
def membership=(membership)
super
self.user ||= membership.try(:user)
self.tenant ||= membership.try(:tenant)
# Time.zone = user.time_zone
end
end
# app/controllers/concerns/current_tenant.rb
module CurrentTenant
extend ActiveSupport::Concern
included do
before_action :current_membership, if: :user_signed_in?
before_action :require_tenant!, if: :user_signed_in?
private
# rubocop:disable Metrics/AbcSize
def current_membership
Current.membership ||= if cookies[:tenant_id]
current_user.memberships.where(tenant_id: cookies[:tenant_id]).take
else
current_user.memberships.count == 1 ? current_user.memberships.first : nil
end
end
# rubocop:enable Metrics/AbcSize
def require_tenant!
redirect_to(tenants_path, notice: t('Please select a tenant')) && return unless current_tenant
end
def current_tenant
Current.tenant ||= Tenant.find_by id: cookies[:tenant_id]
end
helper_method :current_tenant, :current_membership
end
end
Rails.application.routes.draw do
# List tenants...
get '/tenants', to: 'tenants#index', as: 'tenants'
# Switch tenants...
get '/tenants/:id', to: 'tenants#show', as: 'switch_tenant'
end
class TenantsController < ApplicationController
skip_before_action :require_tenant!, only: %i[index show]
# Show a list of the tenants that I have access to:
def index
@memberships = current_user.memberships
end
# Switch tenants:
# Set a cookie, then redirect to that tenant.
def show
tenant = current_user.tenants.find(params[:id])
cookies.permanent[:tenant_id] = tenant.id
redirect_to(session[:return_to] || params[:return_to] || root_path)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment