Module: Liquid2::CachingLoaderMixin

Included in:
CachingFileSystemLoader
Defined in:
lib/liquid2/loaders/mixins.rb

Overview

A mixin that adds caching to a template loader.

Instance Method Summary collapse

Instance Method Details

#cache_key(name, context: nil, **kwargs) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/liquid2/loaders/mixins.rb', line 38

def cache_key(name, context: nil, **kwargs)
  return name unless @namespace_key

  key = (@namespace_key || raise).to_sym
  return "#{kwargs[key]}/#{name}" if kwargs.include?(key)
  return name unless context

  if (namespace = context.globals[@namespace_key || raise])
    "#{namespace}/#{name}"
  else
    name
  end
end

#initialize_cache(auto_reload: true, namespace_key: "", capacity: 300, thread_safe: false) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/liquid2/loaders/mixins.rb', line 8

def initialize_cache(auto_reload: true, namespace_key: "", capacity: 300, thread_safe: false)
  @auto_reload = auto_reload
  @namespace_key = namespace_key
  @cache = if thread_safe
             ThreadSafeLRUCache.new(capacity)
           else
             LRUCache.new(capacity)
           end
end

#load(env, name, globals: nil, context: nil, **kwargs) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/liquid2/loaders/mixins.rb', line 18

def load(env, name, globals: nil, context: nil, **kwargs)
  key = cache_key(name, context: context, **kwargs)

  # @type var template: Liquid2::Template
  # @type var cached_template: Liquid2::Template
  if (cached_template = @cache[key])
    if @auto_reload && cached_template.up_to_date? == false
      template = super
      @cache[key] = template
      template
    else
      cached_template
    end
  else
    template = super
    @cache[key] = template
    template
  end
end