Class: Dry::Effects::Effects::Cache

Inherits:
Module
  • Object
show all
Defined in:
lib/dry/effects/effects/cache.rb

Defined Under Namespace

Classes: CacheEffect

Instance Method Summary collapse

Constructor Details

#initialize(scope = nil, shared: false, **kw) ⇒ Cache

Returns a new instance of Cache.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dry/effects/effects/cache.rb', line 11

def initialize(scope = nil, shared: false, **kw)
  super()

  if !kw.empty?
    scope, as = kw.to_a[0]
  elsif scope.is_a?(::Hash)
    scope, as = scope.to_a[0]
  else
    as = :cache
  end

  fetch_or_store = CacheEffect.new(
    type: :cache,
    name: :fetch_or_store,
    scope: scope
  )

  key = key(shared)

  module_eval do
    Array(as).each do |meth|
      define_method(meth) do |*args, &block|
        if block
          eff = fetch_or_store.(key.(self, args), block)
        else
          eff = fetch_or_store.(key.(self, args, method: meth), -> { super(*args) })
        end

        ::Dry::Effects.yield(eff)
      end
    end
  end
end

Instance Method Details

#cache_key(instance, args, method: Undefined) ⇒ Object



61
62
63
64
65
66
67
# File 'lib/dry/effects/effects/cache.rb', line 61

def cache_key(instance, args, method: Undefined)
  if Undefined.equal?(method)
    [instance, args]
  else
    [instance, method, args]
  end
end

#key(shared) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/dry/effects/effects/cache.rb', line 45

def key(shared)
  if shared
    method(:shared_cache_key)
  else
    method(:cache_key)
  end
end

#shared_cache_key(_, args, method: Undefined) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/dry/effects/effects/cache.rb', line 53

def shared_cache_key(_, args, method: Undefined)
  if Undefined.equal?(method)
    args
  else
    [method, args]
  end
end