Module: Tenantify

Defined in:
lib/tenantify.rb,
lib/tenantify/job.rb,
lib/tenantify/errors.rb,
lib/tenantify/scoped.rb,
lib/tenantify/current.rb,
lib/tenantify/railtie.rb,
lib/tenantify/version.rb,
lib/tenantify/switcher.rb,
lib/tenantify/controller.rb,
lib/tenantify/test_helpers.rb,
lib/tenantify/configuration.rb,
lib/tenantify/resolvers/header.rb,
lib/tenantify/middleware/sidekiq.rb,
lib/tenantify/resolvers/subdomain.rb

Defined Under Namespace

Modules: Controller, Job, Middleware, RelationExtension, Resolvers, Scoped, Switcher, TestHelpers Classes: Configuration, Current, Error, Railtie, TenantMismatchError, TenantNotFoundError, TenantOverrideError

Constant Summary collapse

VERSION =
"0.1.2"

Class Method Summary collapse

Class Method Details

.configurationObject



20
21
22
# File 'lib/tenantify.rb', line 20

def configuration
  @configuration ||= Configuration.new
end

.configure {|configuration| ... } ⇒ Object

Yields:



24
25
26
# File 'lib/tenantify.rb', line 24

def configure
  yield(configuration)
end

.current_tenantObject



28
29
30
# File 'lib/tenantify.rb', line 28

def current_tenant
  Current.tenant
end

.current_tenant=(tenant) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/tenantify.rb', line 32

def current_tenant=(tenant)
  if Current.tenant && tenant && Current.tenant != tenant
    message = "Unsafe tenant override attempted: changing tenant from #{Current.tenant.id} to #{tenant.id}"
    case configuration.audit_overrides
    when :raise
      raise TenantOverrideError, message
    when :log
      if defined?(Rails) && Rails.logger
        Rails.logger.warn("[Tenantify] #{message}")
      else
        warn("[Tenantify] #{message}")
      end
    end
  end
  Current.tenant = tenant
end

.current_tenant_idObject



49
50
51
# File 'lib/tenantify.rb', line 49

def current_tenant_id
  current_tenant&.id
end

.switch_to(tenant, &block) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/tenantify.rb', line 57

def switch_to(tenant, &block)
  old_tenant = Current.tenant
  Current.tenant = tenant
  yield
ensure
  Current.tenant = old_tenant
end

.tenant_classObject



73
74
75
76
77
78
79
80
# File 'lib/tenantify.rb', line 73

def tenant_class
  class_name = configuration.tenant_model
  unless class_name
    raise Tenantify::Error, "tenant_model is not configured. Define it in Tenantify.configure."
  end

  class_name.constantize
end

.tenant_scoped?Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/tenantify.rb', line 53

def tenant_scoped?
  !Current.tenant_scope_disabled
end

.without_tenant(&block) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/tenantify.rb', line 65

def without_tenant(&block)
  old_disabled = Current.tenant_scope_disabled
  Current.tenant_scope_disabled = true
  yield
ensure
  Current.tenant_scope_disabled = old_disabled
end