Module: Apartment::Tenant

Defined in:
lib/apartment/tenant.rb

Class Method Summary collapse

Class Method Details

.create(tenant) ⇒ Object

Delegate lifecycle operations to the adapter.



51
52
53
# File 'lib/apartment/tenant.rb', line 51

def create(tenant)
  adapter.create(tenant)
end

.currentObject

Current tenant name.



35
36
37
# File 'lib/apartment/tenant.rb', line 35

def current
  Current.tenant || Apartment.config&.default_tenant
end

.drop(tenant) ⇒ Object



55
56
57
# File 'lib/apartment/tenant.rb', line 55

def drop(tenant)
  adapter.drop(tenant)
end

.initObject

Initialize: resolve excluded_models shim, then process pinned models.



45
46
47
48
# File 'lib/apartment/tenant.rb', line 45

def init
  resolve_excluded_models_shim
  adapter.process_pinned_models
end

.migrate(tenant, version = nil) ⇒ Object



59
60
61
# File 'lib/apartment/tenant.rb', line 59

def migrate(tenant, version = nil)
  adapter.migrate(tenant, version)
end

.pool_statsObject

Pool stats delegated to pool_manager.



68
69
70
# File 'lib/apartment/tenant.rb', line 68

def pool_stats
  Apartment.pool_manager&.stats || {}
end

.resetObject

Reset to default tenant.



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

def reset
  switch!(Apartment.config&.default_tenant)
end

.seed(tenant) ⇒ Object



63
64
65
# File 'lib/apartment/tenant.rb', line 63

def seed(tenant)
  adapter.seed(tenant)
end

.switch(tenant, &block) ⇒ Object

Switch to a tenant for the duration of the block. Guaranteed cleanup via ensure — tenant context is always restored.

Note: previous_tenant reflects only the immediately preceding tenant for the current switch scope. It is not stacked across nesting levels —after an inner switch completes, previous_tenant resets to nil.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/apartment/tenant.rb', line 12

def switch(tenant, &block)
  raise(ArgumentError, 'Apartment::Tenant.switch requires a block') unless block

  previous = Current.tenant
  Current.tenant = tenant
  Current.previous_tenant = previous
  if tagged_logging?
    Rails.logger.tagged("tenant=#{tenant}", &block)
  else
    yield
  end
ensure
  Current.tenant = previous
  Current.previous_tenant = nil
end

.switch!(tenant) ⇒ Object

Direct switch without block. Discouraged — prefer switch with block.



29
30
31
32
# File 'lib/apartment/tenant.rb', line 29

def switch!(tenant)
  Current.previous_tenant = Current.tenant
  Current.tenant = tenant
end