Class: TemplateRenderer::PartialResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/generators/template_renderer/partial_resolver.rb

Overview

Resolves partial template paths with context-aware searching

Resolution strategy:

  1. Try relative to calling template: ./partials/name.tt

  2. Fall back to all Generator.source_paths searching for partials/name.tt

Constant Summary collapse

PARTIAL_EXTENSION =
'.tt'
PARTIALS_DIR =
'partials'

Instance Method Summary collapse

Constructor Details

#initialize(generator_class) ⇒ PartialResolver

Returns a new instance of PartialResolver.



15
16
17
# File 'lib/generators/template_renderer/partial_resolver.rb', line 15

def initialize(generator_class)
  @generator_class = generator_class
end

Instance Method Details

#resolve(name, binding) ⇒ String

Resolve a partial name to its absolute file path

Parameters:

  • name (String)

    The partial name (without .tt extension)

  • binding (Binding)

    The binding context from the caller

Returns:

  • (String)

    Absolute path to the partial file

Raises:



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/generators/template_renderer/partial_resolver.rb', line 25

def resolve(name, binding)
  caller_file = caller_file_from_binding(binding)
  partial_filename = "#{name}#{PARTIAL_EXTENSION}"

  # Try relative to caller first
  if caller_file
    relative_path = File.join(File.dirname(caller_file), PARTIALS_DIR, partial_filename)
    return File.expand_path(relative_path) if File.exist?(relative_path)
  end

  # Fall back to searching all source paths
  searched = search_source_paths(partial_filename)
  return searched[:found] if searched[:found]

  # Not found - raise with helpful error
  raise TemplateNotFoundError.new(
    "Partial '#{name}' not found",
    partial_name: name,
    searched_paths: search_paths(name, binding)
  )
end

#search_paths(name, binding) ⇒ Object

Get all paths that were searched (for error messages)



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/generators/template_renderer/partial_resolver.rb', line 48

def search_paths(name, binding)
  paths = []
  partial_filename = "#{name}#{PARTIAL_EXTENSION}"

  # Add relative path if available
  caller_file = caller_file_from_binding(binding)
  if caller_file
    relative_path = File.join(File.dirname(caller_file), PARTIALS_DIR, partial_filename)
    paths << relative_path
  end

  # Add all source path possibilities (including subdirectories)
  source_paths.each do |source_path|
    paths << File.join(source_path, PARTIALS_DIR, partial_filename)

    # Also include subdirectories (e.g., templates/common/partials/, templates/helpers/partials/)
    Dir.glob(File.join(source_path, '*', PARTIALS_DIR)).each do |subdir|
      paths << File.join(subdir, partial_filename)
    end
  end

  paths
end