Class: ViewComponentSubtemplates::SubTemplate

Inherits:
Object
  • Object
show all
Defined in:
lib/view_component_subtemplates/sub_template.rb

Overview

Represents a single sub-template file associated with a ViewComponent. This class is responsible for parsing the template, extracting its arguments, and defining the corresponding ‘call_*` method on the component class.

PUBLIC API - The following methods are guaranteed to be stable across minor versions:

  • #component: Returns the associated component class.

  • #path: Returns the absolute path to the template file.

  • #template_name: Returns the short name of the template (e.g., ‘header`).

  • #explicit_locals: Returns an array of symbols for the template’s arguments.

  • #source: Returns the raw source code of the template file.

PRIVATE API - All other methods are subject to change without notice.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(component:, path:, template_name:) ⇒ SubTemplate

Returns a new instance of SubTemplate.



21
22
23
24
25
26
27
# File 'lib/view_component_subtemplates/sub_template.rb', line 21

def initialize(component:, path:, template_name:)
  @component = component
  @path = path
  @template_name = template_name
  @source = nil # Lazily loaded
  @explicit_locals = nil # Lazily loaded
end

Instance Attribute Details

#componentObject (readonly)

PUBLIC API



19
20
21
# File 'lib/view_component_subtemplates/sub_template.rb', line 19

def component
  @component
end

#pathObject (readonly)

PUBLIC API



19
20
21
# File 'lib/view_component_subtemplates/sub_template.rb', line 19

def path
  @path
end

#template_nameObject (readonly)

PUBLIC API



19
20
21
# File 'lib/view_component_subtemplates/sub_template.rb', line 19

def template_name
  @template_name
end

Instance Method Details

#compile_to_componentObject

This is the main entry point for the class from the compiler extension



38
39
40
41
42
# File 'lib/view_component_subtemplates/sub_template.rb', line 38

def compile_to_component
  validate_file_exists!
  compiled_source = compile_erb_source
  define_render_method(compiled_source, explicit_locals)
end

#explicit_localsObject



33
34
35
# File 'lib/view_component_subtemplates/sub_template.rb', line 33

def explicit_locals
  @explicit_locals ||= extract_explicit_locals_from_source
end

#sourceObject



29
30
31
# File 'lib/view_component_subtemplates/sub_template.rb', line 29

def source
  @source ||= File.read(path)
end