Module: PgRls::Tenant

Defined in:
lib/pg_rls/tenant.rb

Overview

Tenant Controller

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.tenantObject (readonly)

Returns the value of attribute tenant.



18
19
20
# File 'lib/pg_rls/tenant.rb', line 18

def tenant
  @tenant
end

Class Method Details

.fetchObject



20
21
22
23
24
25
26
27
28
# File 'lib/pg_rls/tenant.rb', line 20

def fetch
  @fetch ||= tenant.find_by_tenant_id(
    PgRls.connection_class.connection.execute(
      "SELECT current_setting('rls.tenant_id')"
    ).getvalue(0, 0)
  )
rescue ActiveRecord::StatementInvalid
  'no tenant is selected'
end

.find_tenant(resource) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/pg_rls/tenant.rb', line 30

def find_tenant(resource)
  @tenant = nil

  PgRls.search_methods.each do |method|
    @method = method
    @tenant ||= PgRls.main_model.send("find_by_#{method}", resource)
  rescue NoMethodError => e
    @error = e
  end
end

.switch(resource) ⇒ Object



7
8
9
10
11
12
13
14
15
16
# File 'lib/pg_rls/tenant.rb', line 7

def switch(resource)
  connection_adapter = PgRls.connection_class
  find_tenant(resource)
  connection_adapter.connection.execute(format('SET rls.tenant_id = %s',
                                               connection_adapter.connection.quote(tenant.tenant_id)))
  "RLS changed to '#{tenant.send(@method)}'"
rescue StandardError => e
  puts 'connection was not made'
  puts @error || e
end