Class: Galleruby::Template

Inherits:
Object
  • Object
show all
Defined in:
lib/galleruby/template.rb

Direct Known Subclasses

TemplateDependencyCalculator

Constant Summary collapse

@@cache =
{}

Instance Method Summary collapse

Constructor Details

#initialize(file, config, output_filename = nil, base_directory = nil) ⇒ Template

Returns a new instance of Template.



8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/galleruby/template.rb', line 8

def initialize(file, config, output_filename=nil, base_directory=nil)
    @config = config

    file = template_path file
    if not @@cache.has_key? file then
        @@cache[file] = Haml::Engine.new(File.read(file))
    end

    @engine = @@cache[file]
    @locals = {}
    @output_filename = output_filename
    @base_directory = base_directory
end

Instance Method Details

#base_relative(path) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/galleruby/template.rb', line 61

def base_relative(path)
    return path if @output_filename.nil? or @base_directory.nil?
    components = File.dirname(@output_filename).split '/'
    if components.first != @base_directory
        components = [".."] * components.length + [@base_directory]
    else
        components = [".."] * (components.length - 1)
    end
    components << path

    return components.join('/')
end

#include_for_each(file, elements) ⇒ Object



50
51
52
53
54
# File 'lib/galleruby/template.rb', line 50

def include_for_each(file, elements)
    elements.map { |element|
        include_template(file, element)
    }.join("\n")
end

#include_template(file, locals = {}) ⇒ Object



56
57
58
59
# File 'lib/galleruby/template.rb', line 56

def include_template(file, locals={})
    template = self.class.new(file, @config, @output_filename, @base_directory)
    template.render(@locals.merge(locals))
end

#render(locals = {}) ⇒ Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/galleruby/template.rb', line 39

def render(locals={})
    if @output_filename.nil?
        @output_filename = ''
    end

    @locals = locals
    @locals[:config] = @config

    @engine.render(self, @locals)
end

#render_to(filename, locals = {}, base = nil) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/galleruby/template.rb', line 26

def render_to(filename, locals={}, base=nil)
    @output_filename = filename
    @base_directory = base

    content = render(locals)
    File.open(filename, 'w') do |file|
        file.write(content)
    end

    @base_directory = nil
    @output_filename = nil
end

#template_path(name) ⇒ Object



22
23
24
# File 'lib/galleruby/template.rb', line 22

def template_path(name)
    "#{@config[:templates]}/#{name}.haml"
end