Module: Ec::Pg::Context

Defined in:
lib/ec/pg/context.rb

Overview

Thread-safe store for the current multi-tenant context.

Each key is namespaced under a per-thread hash so that Sidekiq workers, Puma threads, and Fiber-based servers never bleed context across requests.

Usage (low-level):

Context.set(tenant_id: "abc")
Context.get(:tenant_id)         # => "abc"
Context.with(tenant_id: "xyz") { ... }   # restores previous value on exit
Context.clear!

Constant Summary collapse

ThreadKey =
:__ec_pg_activerecord_multi_tenant
ManagedKeys =
%i[shard schema].freeze

Class Method Summary collapse

Class Method Details

.active?Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/ec/pg/context.rb', line 63

def active?
  ManagedKeys.any? { |k| store.key?(k) }
end

.clear!Object



67
68
69
# File 'lib/ec/pg/context.rb', line 67

def clear!
  Thread.current[ThreadKey] = {}
end

.currentObject

Returns a shallow copy of the entire current context hash.



31
32
33
# File 'lib/ec/pg/context.rb', line 31

def current
  store.dup
end

.delete(key) ⇒ Object

Removes key from the current thread’s context.



46
47
48
# File 'lib/ec/pg/context.rb', line 46

def delete(key)
  store.delete(key.to_sym)
end

.get(key) ⇒ Object

Returns the value stored under key, or nil.



36
37
38
# File 'lib/ec/pg/context.rb', line 36

def get(key)
  store[key.to_sym]
end

.schemaObject



27
# File 'lib/ec/pg/context.rb', line 27

def schema;             get(:schema);            end

.schema=(val) ⇒ Object



28
# File 'lib/ec/pg/context.rb', line 28

def schema=(val);       set(schema: val);       end

.set(key_values = {}) ⇒ Object

Stores value under key for the current thread.



41
42
43
# File 'lib/ec/pg/context.rb', line 41

def set(key_values = {})
  store.merge!(key_values)
end

.shardObject

Convenience accessors ————————————————-



25
# File 'lib/ec/pg/context.rb', line 25

def shard;              get(:shard);             end

.shard=(val) ⇒ Object



26
# File 'lib/ec/pg/context.rb', line 26

def shard=(val);        set(shard: val);        end

.storeObject



71
72
73
# File 'lib/ec/pg/context.rb', line 71

def store
  Thread.current[ThreadKey] ||= {}
end

.with(key_values = {}) ⇒ Object

Yields with key temporarily set to value, then restores the previous value (or removes the key if it wasn’t set before).



52
53
54
55
56
57
58
59
60
61
# File 'lib/ec/pg/context.rb', line 52

def with(key_values = {})
  keys = key_values.keys
  stashed = store.slice(*keys)
  set(key_values)
  yield
ensure
  store.except!(*keys)
  set(stashed)
  store.compact!
end