module Tenantify::Tenant

Responsible for managing the current tenant. All useful methods {#using}, {#use!}, and {#current} have aliases at {Tenantify} module.

Threading Notes

The {Tenantify::Tenant} module uses thread variables to store the current tenant. This means that when a new thread is spawned, the tenant has to be set manually.

Public Class Methods

current() click to toggle source

Returns the current tenant.

@return [Symbol] the current tenant.

# File lib/tenantify/tenant.rb, line 40
def self.current
  Thread.current.thread_variable_get(:tenant)
end
use!(tenant) click to toggle source

Sets the given tenant from now on.

@param [Symbol] the tenant to set. @return [Symbol] the set tenant.

# File lib/tenantify/tenant.rb, line 33
def self.use! tenant
  Thread.current.thread_variable_set(:tenant, tenant)
end
using(tenant) { || ... } click to toggle source

Runs the given block for a tenant.

@param [Symbol] the tenant to run the code for. @yield the code to run. @return the returning value of the block.

@example Getting data from a storage of a particular tenant:

data = Tenant.using :the_tenant do
  Storage.current.get_data
end
# File lib/tenantify/tenant.rb, line 20
def self.using tenant
  original_tenant = Thread.current.thread_variable_get(:tenant)

  Thread.current.thread_variable_set(:tenant, tenant)
  yield
ensure
  Thread.current.thread_variable_set(:tenant, original_tenant)
end