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



64
65
66
67
68
69
# File 'lib/action_policy/policy/cache.rb', line 64

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



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/action_policy/policy/cache.rb', line 48

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

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

#cache(*parts, **options) ⇒ Object



71
72
73
74
75
76
77
78
79
80
# File 'lib/action_policy/policy/cache.rb', line 71

def cache(*parts, **options)
  key = cache_key(*parts)
  ActionPolicy.cache_store.then do |store|
    res = store.read(key)
    next res unless res.nil?
    res = yield
    store.write(key, res, options)
    res
  end
end

#cache_key(*parts) ⇒ Object



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

def cache_key(*parts)
  [
    cache_namespace,
    *parts
  ].map { _1._policy_cache_key }.join("/")
end

#cache_namespaceObject



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

def cache_namespace() = ActionPolicy::CACHE_NAMESPACE

#context_cache_keyObject



44
45
46
# File 'lib/action_policy/policy/cache.rb', line 44

def context_cache_key
  authorization_context.map { _2._policy_cache_key.to_s }.join("/")
end

#rule_cache_key(rule) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/action_policy/policy/cache.rb', line 35

def rule_cache_key(rule)
  cache_key(
    context_cache_key,
    record,
    self.class,
    rule
  )
end