Module: Luoma::CachingLoaderMixin

Included in:
CachingFileSystemLoader
Defined in:
lib/luoma/loaders/mixins.rb,
sig/luoma/loaders/mixins.rbs

Overview

A mixin that adds caching to a template loader.

Instance Method Summary collapse

Instance Method Details

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

Parameters:

  • name (String)
  • context: (RenderContext, nil) (defaults to: nil)
  • kwargs (Object)

Returns:

  • (String)


38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/luoma/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

Parameters:

  • auto_reload: (Boolean) (defaults to: true)
  • namespace_key: (::String) (defaults to: "")
  • capacity: (::Integer) (defaults to: 300)
  • thread_safe: (Boolean) (defaults to: false)

Returns:

  • (Object)


8
9
10
11
12
13
14
15
16
# File 'lib/luoma/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) ⇒ Template

Parameters:

Returns:



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

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

  # @type var template: Template
  # @type var cached_template: 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