Class: RailsAIPromptable::TemplateRegistry

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_ai_promptable/template_registry.rb

Class Method Summary collapse

Class Method Details

.clear!Object

Clear all registered templates



63
64
65
# File 'lib/rails_ai_promptable/template_registry.rb', line 63

def clear!
  @templates = {}
end

.get(name) ⇒ Object

Get a template by name



18
19
20
# File 'lib/rails_ai_promptable/template_registry.rb', line 18

def get(name)
  templates[name.to_sym]
end

.listObject

List all registered template names



68
69
70
# File 'lib/rails_ai_promptable/template_registry.rb', line 68

def list
  templates.keys
end

.load_from_directory(directory_path) ⇒ Object

Load templates from a directory Each file should be named <template_name>.yml or <template_name>.txt



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rails_ai_promptable/template_registry.rb', line 43

def load_from_directory(directory_path)
  return unless Dir.exist?(directory_path)

  Dir.glob(File.join(directory_path, "*")).each do |file_path|
    next unless File.file?(file_path)

    name = File.basename(file_path, ".*")

    if file_path.end_with?(".yml", ".yaml")
      content = YAML.load_file(file_path)
      template = content.is_a?(Hash) ? content["template"] : content.to_s
    else
      template = File.read(file_path)
    end

    register(name, template) if template
  end
end

.load_from_file(file_path) ⇒ Object

Load templates from a YAML file



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rails_ai_promptable/template_registry.rb', line 23

def load_from_file(file_path)
  return unless File.exist?(file_path)

  begin
    loaded_templates = YAML.load_file(file_path)
    return unless loaded_templates.is_a?(Hash)

    loaded_templates.each do |name, template|
      register(name, template)
    end
  rescue Psych::SyntaxError => e
    # Log the error but don't raise - invalid YAML files are silently skipped
    if defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger
      Rails.logger.warn("[rails_ai_promptable] Failed to load templates from #{file_path}: #{e.message}")
    end
  end
end

.register(name, template) ⇒ Object

Register a template with a name



13
14
15
# File 'lib/rails_ai_promptable/template_registry.rb', line 13

def register(name, template)
  templates[name.to_sym] = template
end

.templatesObject



8
9
10
# File 'lib/rails_ai_promptable/template_registry.rb', line 8

def templates
  @templates ||= {}
end