Class: Reactor::Cache::Permission

Inherits:
Object
  • Object
show all
Defined in:
lib/reactor/cache/permission.rb

Constant Summary collapse

BACKING_CACHE_EXPIRATION =
5

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePermission

Returns a new instance of Permission.



10
11
12
# File 'lib/reactor/cache/permission.rb', line 10

def initialize
  @@backing_storage ||= ActiveSupport::Cache::MemoryStore.new({ size: 1.megabyte })
end

Class Method Details

.instanceObject



6
7
8
# File 'lib/reactor/cache/permission.rb', line 6

def self.instance
  new
end

Instance Method Details

#invalidate(user) ⇒ Object



27
28
29
30
31
32
33
34
# File 'lib/reactor/cache/permission.rb', line 27

def invalidate(user)
  # Rails 7.1+ versions don't allow nil values and empty string as cache keys.
  if user.present?
    @@backing_storage.delete(user.to_s)
  else
    Rails.logger.warn "Reactor::Cache::Permission: Skipping cache invalidation because the key derived from user.to_s was blank."
  end
end

#lookup(user, key) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/reactor/cache/permission.rb', line 14

def lookup(user, key)
  cache_entry = @@backing_storage.fetch(user.to_s, expires_in: BACKING_CACHE_EXPIRATION.minutes) do
    { key => yield }
  end
  if cache_entry.key?(key)
    cache_entry[key]
  else
    result = yield
    @@backing_storage.write(user.to_s, cache_entry.merge({ key => result }), expires_in: BACKING_CACHE_EXPIRATION.minutes)
    result
  end
end