class AudioGlue::TemplateLoader

Loads .glue templates and caches them.

@example

loader = AudioGlue::TemplateLoader.new('/project/audio_templates/')

# load and cache "/project/audio_templates/john/hi.glue"
loader.get('john/hi') # => subclass of AudioGlue::Template

Constants

TEMPLATE_EXT

Extension of template files.

Attributes

base_path[R]

@attr_reader base_path [String] path to a directory with templates

cache[R]

@attr_reader cache [Hash<String, Class>] cached templates, key is a path

to a template file, value is a subclass of {AudioGlue::Template}

Public Class Methods

new(base_path, opts = {}) click to toggle source

@param base_path [String] path to a directory with templates @param opts [Hash] options @option opts :helper [Module] module which provides custom methods

for templates.
# File lib/audio_glue/template_loader.rb, line 24
def initialize(base_path, opts = {})
  @base_path = base_path
  @helper    = opts.delete(:helper)
  @cache     = {}
end

Public Instance Methods

get(template_name) click to toggle source

Load and cache the template from a .glue template file.

@param template_name [String] name of template in base_path directory

@return [Class] a subclass of {AudioGlue::Template}

# File lib/audio_glue/template_loader.rb, line 35
def get(template_name)
  path = absolute_path(template_name)
  @cache[path] ||= load_template_from_file(path)
end
reset_cache!() click to toggle source

Reset the cache.

@return [Hash] empty cache

# File lib/audio_glue/template_loader.rb, line 43
def reset_cache!
  @cache.clear
end

Private Instance Methods

absolute_path(template_name) click to toggle source

Calculate the absolute path to a file from a template name.

@param template_name [String] name of template in base_path directory

@return [String] absolute path to a template file

# File lib/audio_glue/template_loader.rb, line 54
def absolute_path(template_name)
  File.join(@base_path, "#{template_name}.#{TEMPLATE_EXT}")
end
load_template_from_file(path) click to toggle source

Read a .glue template file and create a template class from it.

@param path [String] absolute path to .glue template file

@return [Class] a subclass of {AudioGlue::Template}

# File lib/audio_glue/template_loader.rb, line 64
def load_template_from_file(path)
  Class.new(AudioGlue::Template).tap do |template|
    content = File.read(path)
    template.path = path
    template.send(:include, @helper) if @helper
    template.instance_eval(content, path)
  end
rescue Errno::ENOENT => err
  raise AudioGlue::LoadTemplateError, err.message
rescue SyntaxError, NameError => err
  raise AudioGlue::LoadTemplateError, err.message, err.backtrace
end