Class: ActiveRecord::Tenanted::TenantSelector

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/tenanted/tenant_selector.rb

Overview

If config.active_record_tenanted.connection_class is set, this middleware will be loaded automatically, and will use config.active_record_tenanted.tenant_resolver to determine the appropriate tenant for the request.

If no tenant is resolved, the request will be executed without wrapping it in a tenanted context. Application code will be free to set the tenant as needed.

If a tenant is resolved and the tenant exists, the application will be locked to that tenant’s database for the duration of the request.

If a tenant is resolved, but the tenant does not exist, a 404 response will be returned.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ TenantSelector

Returns a new instance of TenantSelector.



21
22
23
# File 'lib/active_record/tenanted/tenant_selector.rb', line 21

def initialize(app)
  @app = app
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



19
20
21
# File 'lib/active_record/tenanted/tenant_selector.rb', line 19

def app
  @app
end

Instance Method Details

#call(env) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/active_record/tenanted/tenant_selector.rb', line 25

def call(env)
  request = ActionDispatch::Request.new(env)
  tenant_name = tenant_resolver.call(request)

  if tenant_name.blank?
    # run the request without wrapping it in a tenanted context
    @app.call(env)
  elsif tenanted_class.tenant_exist?(tenant_name)
    tenanted_class.with_tenant(tenant_name) { @app.call(env) }
  else
    raise ActiveRecord::Tenanted::TenantDoesNotExistError, "Tenant not found: #{tenant_name.inspect}"
  end
end

#tenant_resolverObject



49
50
51
# File 'lib/active_record/tenanted/tenant_selector.rb', line 49

def tenant_resolver
  @tenanted_resolver ||= Rails.application.config.active_record_tenanted.tenant_resolver
end

#tenanted_classObject



39
40
41
42
43
# File 'lib/active_record/tenanted/tenant_selector.rb', line 39

def tenanted_class
  # Note: we'll probably want to cache this when we look at performance, but don't cache it
  # when class reloading is enabled.
  tenanted_class_name.constantize
end

#tenanted_class_nameObject



45
46
47
# File 'lib/active_record/tenanted/tenant_selector.rb', line 45

def tenanted_class_name
  @tenanted_class_name ||= Rails.application.config.active_record_tenanted.connection_class
end