Class: Liquid2::FileSystemLoader

Inherits:
TemplateLoader show all
Defined in:
lib/liquid2/loaders/file_system_loader.rb

Overview

A template loader that reads template from a file system.

Direct Known Subclasses

CachingFileSystemLoader

Instance Method Summary collapse

Methods inherited from TemplateLoader

#load

Constructor Details

#initialize(search_path, default_extension: nil) ⇒ FileSystemLoader

Returns a new instance of FileSystemLoader.



10
11
12
13
14
15
16
17
18
19
# File 'lib/liquid2/loaders/file_system_loader.rb', line 10

def initialize(search_path, default_extension: nil)
  super()
  @search_path = if search_path.is_a?(Array)
                   search_path.map { |p| Pathname.new(p) }
                 else
                   [Pathname.new(search_path)]
                 end

  @default_extension = default_extension
end

Instance Method Details

#get_source(_env, name, context: nil, **_kwargs) ⇒ Object



21
22
23
24
25
26
# File 'lib/liquid2/loaders/file_system_loader.rb', line 21

def get_source(_env, name, context: nil, **_kwargs)
  path = resolve_path(name)
  mtime = path.mtime
  up_to_date = -> { path.mtime == mtime }
  TemplateSource.new(source: path.read, name: path.to_s, up_to_date: up_to_date)
end

#resolve_path(template_name) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/liquid2/loaders/file_system_loader.rb', line 28

def resolve_path(template_name)
  template_path = Pathname.new(template_name)

  # Append the default file extension if needed.
  if @default_extension && template_path.extname.empty?
    template_path = template_path.sub_ext(@default_extension || raise)
  end

  # Don't alow template names to escape the search path with "../".
  template_path.each_filename do |part|
    if part == ".."
      raise LiquidTemplateNotFoundError.new("template not found #{template_name}",
                                            nil)
    end
  end

  # Search each path in turn.
  @search_path.each do |path|
    source_path = path.join(template_path)
    return source_path if source_path.file?
  end

  raise LiquidTemplateNotFoundError.new("template not found #{template_name}", nil)
end