Class: Luoma::FileSystemLoader

Inherits:
TemplateLoader show all
Defined in:
lib/luoma/loaders/file_system_loader.rb,
sig/luoma/loaders/file_system_loader.rbs

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.

Parameters:

  • search_path (String, Array[String])
  • default_extension: (String, nil) (defaults to: nil)


8
9
10
11
12
13
14
15
16
17
# File 'lib/luoma/loaders/file_system_loader.rb', line 8

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



19
20
21
22
23
24
# File 'lib/luoma/loaders/file_system_loader.rb', line 19

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.basename.to_s, up_to_date: up_to_date)
end

#resolve_path(template_name) ⇒ Pathname

Parameters:

  • template_name (String)

Returns:

  • (Pathname)

Raises:



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

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

  # TODO: better relative path check

  # Don't alow template names to escape the search path with "../".
  template_path.each_filename do |part|
    next unless part == ".."

    raise TemplateNotFoundError.new("template not found #{template_name}")
  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 TemplateNotFoundError.new("template not found #{template_name}")
end