Module: Tenantify::Tenant

Defined in:
lib/tenantify/tenant.rb

Overview

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

Threading Notes

The 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.

Class Method Summary collapse

Class Method Details

.currentSymbol

Returns the current tenant.

Returns:

  • (Symbol)

    the current tenant.



40
41
42
# File 'lib/tenantify/tenant.rb', line 40

def self.current
  Thread.current.thread_variable_get(:tenant)
end

.use!(tenant) ⇒ Symbol

Sets the given tenant from now on.

Parameters:

  • the (Symbol)

    tenant to set.

Returns:

  • (Symbol)

    the set tenant.



33
34
35
# File 'lib/tenantify/tenant.rb', line 33

def self.use! tenant
  Thread.current.thread_variable_set(:tenant, tenant)
end

.using(tenant) { ... } ⇒ Object

Runs the given block for a tenant.

Examples:

Getting data from a storage of a particular tenant:

data = Tenant.using :the_tenant do
  Storage.current.get_data
end

Parameters:

  • the (Symbol)

    tenant to run the code for.

Yields:

  • the code to run.

Returns:

  • the returning value of the block.



20
21
22
23
24
25
26
27
# 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