Module: ActionPolicy::Policy::Cache

Included in:
Base
Defined in:
lib/action_policy/policy/cache.rb

Overview

Provides long-lived cache through ActionPolicy.cache_store.

NOTE: if cache_store is nil then we silently skip all the caching.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



21
22
23
# File 'lib/action_policy/policy/cache.rb', line 21

def included(base)
  base.extend ClassMethods
end

Instance Method Details

#apply(rule) ⇒ Object

rubocop: enable Metrics/AbcSize



54
55
56
57
58
59
# File 'lib/action_policy/policy/cache.rb', line 54

def apply(rule)
  return super if ActionPolicy.cache_store.nil? ||
                  !self.class.cached_rules.key?(rule)

  apply_with_cache(rule) { super }
end

#apply_with_cache(rule) ⇒ Object

rubocop: disable Metrics/AbcSize



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/action_policy/policy/cache.rb', line 40

def apply_with_cache(rule)
  options = self.class.cached_rules.fetch(rule)
  key = cache_key(rule)

  ActionPolicy.cache_store.then do |store|
    @result = store.read(key)
    next result.value unless result.nil?
    yield
    store.write(key, result, options)
    result.value
  end
end

#cache_key(rule) ⇒ Object



30
31
32
33
# File 'lib/action_policy/policy/cache.rb', line 30

def cache_key(rule)
  "#{cache_namespace}/#{context_cache_key}/" \
  "#{record._policy_cache_key}/#{self.class.name}/#{rule}"
end

#cache_namespaceObject



26
27
28
# File 'lib/action_policy/policy/cache.rb', line 26

def cache_namespace
  ActionPolicy::CACHE_NAMESPACE
end

#context_cache_keyObject



35
36
37
# File 'lib/action_policy/policy/cache.rb', line 35

def context_cache_key
  authorization_context.map { |_k, v| v._policy_cache_key.to_s }.join("/")
end