Class: Rcurse::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/rcurse/engine.rb

Overview

The Rcurse engine

Class Method Summary (collapse)

Class Method Details

+ (String) render(content, context = Context.new)

Render a template

Parameters:

  • content (String) —

    A String containing the Rcurse template

  • context (Rcurse::Context) (defaults to: Context.new) —

    a context for the template

Returns:

  • (String) —

    The rendered template



11
12
13
14
15
16
17
18
19
20
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
48
49
50
51
52
# File 'lib/rcurse/engine.rb', line 11

def self.render content, context = Context.new

    # find Rcurse calls in template
    # Regex explaination - http://goo.gl/vpKPeZ
    content.gsub /({{|{%=|{%)(.+?)[}|%]}/ do |match|
        # return unaltered if nothing is done
        result = match

        type = $1
        content = $2

        # determine what to do
        # helper calls start with {{
        # silent eval calls start with {%
        # eval calls start with {%=
        case type
        when "{{"
            content_parts = content.chomp.split(" ")
            name = content_parts[0]

            # omit the first element
            args = content_parts[1..-1]

            # check if helper exists
            if Rcurse::helpers[name].is_a? Rcurse::Helper then
                result = Rcurse::helpers[name].callback.call(args, context)
            end
        when "{%"
            # evaluate code inside {% %}
            context.eval(content)

            # remove code from template
            result = ""
        when "{%="
            # evaluate code and write result to template
            result = context.eval(content)
        end

        # return the result. replacing the Rcurse call
        result
    end
end

+ (String) render_file(filename, out_filename = nil, context = Context.new)

Render a template file, optionally writing output to another file

Parameters:

  • filename (String) —

    A String containing the Rcurse template

  • out_filename (String) (defaults to: nil) —

    Optional, file to write output to

  • context (Rcurse::Context) (defaults to: Context.new) —

    a context for the template

Returns:

  • (String) —

    The rendered template



60
61
62
63
64
65
66
67
68
69
# File 'lib/rcurse/engine.rb', line 60

def self.render_file filename, out_filename = nil, context = Context.new
    content = File.read(filename)
    context.path = File.dirname(filename)
    rendered_content = self.render(content, context)

    # write rendered content to output file if specified
    File.open(out_filename, "w+") { |file| file.write(rendered_content) } if out_filename

    return rendered_content
end