Class: Spectre::Prompt

Inherits:
Object
  • Object
show all
Defined in:
lib/spectre/prompt.rb

Defined Under Namespace

Classes: Context

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.prompts_pathObject (readonly)

Returns the value of attribute prompts_path.



9
10
11
# File 'lib/spectre/prompt.rb', line 9

def prompts_path
  @prompts_path
end

Class Method Details

.render(template:, locals: {}) ⇒ String

Render a prompt by reading and rendering the YAML template

Parameters:

  • template (String)

    The path to the template file, formatted as ‘folder1/folder2/prompt’

  • locals (Hash) (defaults to: {})

    Variables to be passed to the template for rendering

Returns:

  • (String)

    Rendered prompt



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/spectre/prompt.rb', line 21

def render(template:, locals: {})
  path, prompt = split_template(template)
  file_path = prompt_file_path(path, prompt)

  raise "Prompt file not found: #{file_path}" unless File.exist?(file_path)

  # Preprocess the locals before rendering the YAML file
  preprocessed_locals = preprocess_locals(locals)

  template_content = File.read(file_path)
  erb_template = ERB.new(template_content)

  context = Context.new(preprocessed_locals)
  rendered_prompt = erb_template.result(context.get_binding)

  # YAML.safe_load returns a hash, so fetch the correct part based on the prompt
  parsed_yaml = YAML.safe_load(rendered_prompt)[prompt]

  # Convert special characters back after YAML processing
  convert_special_chars_back(parsed_yaml)
rescue Errno::ENOENT
  raise "Template file not found at path: #{file_path}"
rescue Psych::SyntaxError => e
  raise "YAML Syntax Error in file #{file_path}: #{e.message}"
rescue StandardError => e
  raise "Error rendering prompt for template '#{template}': #{e.message}"
end