Class: Serbea::TemplateEngine

Inherits:
Erubi::Engine
  • Object
show all
Defined in:
lib/serbea/template_engine.rb

Constant Summary collapse

FRONT_MATTER_REGEXP =
%r!\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)!m.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, properties = {}) ⇒ TemplateEngine

Returns a new instance of TemplateEngine.



68
69
70
71
72
# File 'lib/serbea/template_engine.rb', line 68

def initialize(input, properties={})
  properties[:regexp] = /{%(={1,2}|-|\#|%)?(.*?)([-=])?%}([ \t]*\r?\n)?/m
  properties[:strip_front_matter] = true unless properties.key?(:strip_front_matter)
  super process_serbea_input(input, properties), properties
end

Class Method Details

.directive(new_directive, directive_resolution) ⇒ Object



17
18
19
# File 'lib/serbea/template_engine.rb', line 17

def self.directive(new_directive, directive_resolution)
  directives[new_directive.to_s] = directive_resolution
end

.directivesObject



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
53
54
# File 'lib/serbea/template_engine.rb', line 21

def self.directives
  @directives ||= {
    "@" => ->(code, buffer) do
      pieces = code.split(" ")
      if pieces[0].start_with?(/[A-Z]/) # Ruby class name
        pieces[0].prepend " "
        pieces[0] << ".new("
      else # string or something else
        pieces[0].prepend "("
      end

      includes_block = false
      pieces.reverse.each do |piece|
        if piece == "do" && (pieces.last == "do" || pieces.last.end_with?("|"))
          piece.prepend(") ")
          includes_block = true
          break
        end
      end

      if includes_block
        buffer << "{%= render#{pieces.join(" ")} %}"
      else
        pieces.last << ")"
        buffer << "{%= render#{pieces.join(" ")} %}"
      end
    end,
    "`" => ->(code, buffer) do
      buffer << "{%= %`"
      buffer << code.gsub(%r("([^\\]?)\#{(.*?)}"), "\"\\1\#{h(\\2)}\"")
      buffer << ".strip %}"
    end
  }
end

.front_matter_preambleObject



60
61
62
# File 'lib/serbea/template_engine.rb', line 60

def self.front_matter_preamble
  @front_matter_preamble ||= "frontmatter = YAML.load"
end

.front_matter_preamble=(varname) ⇒ Object



56
57
58
# File 'lib/serbea/template_engine.rb', line 56

def self.front_matter_preamble=(varname)
  @front_matter_preamble = varname
end

.has_yaml_header?(template) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/serbea/template_engine.rb', line 64

def self.has_yaml_header?(template)
  template.lines.first&.match? %r!\A---\s*\r?\n!
end

Instance Method Details

#process_serbea_input(template, properties) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/serbea/template_engine.rb', line 74

def process_serbea_input(template, properties)
  buff = ""
  
  string = template.dup
  if properties[:strip_front_matter] && self.class.has_yaml_header?(string)
    if string = string.match(FRONT_MATTER_REGEXP)
      require "yaml" if self.class.front_matter_preamble.include?(" = YAML.load")

      string = "{% #{self.class.front_matter_preamble} <<~YAMLDATA\n" + 
        string[1].sub(/^---\n/,'') +
        "YAMLDATA\n%}" +
        string[2].sub(/^---\n/, '') +
        string.post_match
    end
  end
  
  # Ensure the raw "tag" will strip out all ERB-style processing
  until string.empty?
    text, code, string = string.partition(/{% raw %}(.*?){% endraw %}/m)
  
    buff << text
    if code.length > 0
      buff << $1.
        gsub("{{", "__RAW_START_PRINT__").
        gsub("}}", "__RAW_END_PRINT__").
        gsub("{%", "__RAW_START_EVAL__").
        gsub("%}", "__RAW_END_EVAL__")
    end
  end

  # Process any pipelines
  string = buff
  buff = ""
  until string.empty?
    text, code, string = string.partition(/{{(.*?)}}/m)
  
    buff << text
    if code.length > 0
      original_line_length = code.lines.size

      s = StringScanner.new($1)
      escaped_segment = ""
      segments = []
      until s.eos?
        portion = s.scan_until(/\|>?/)
        if portion
          if portion.end_with?('\|')
            # the pipe is escaped, so save that for later
            escaped_segment += portion.sub(/\\\|$/, "|")
          elsif escaped_segment.length > 0
            # we already have escaped content, so finish that up
            segments << escaped_segment + portion.sub(/\|>?$/, "")
            escaped_segment = ""
          else
            # let's find out if this is actionable now
            if s.check(/\|/)
              # nope, the next character is another pipe, so let's escape
              s.pos += 1
              escaped_segment += portion + "|"
            else
              # finally, we have liftoff!
              segments << portion.sub(/\|>?$/, "")
            end
          end
        else
          # we've reached the last bit of the code
          if escaped_segment.length > 0
            # escape and get the rest
            segments << escaped_segment + s.rest
          else
            # or just the rest will do
            segments << s.rest
          end
          s.terminate
        end
      end

      segments[0] = "pipeline(binding, (#{segments[0].strip}))"
      segments[1..-1].each_with_index do |segment, index|
        filter, args = segment.strip.match(/([^ :]*)(.*)/m).captures
        segments[index + 1] = ".filter(:" + filter
        if args == ""
          segments[index + 1] += ")"
        else
          segments[index + 1] += "," + args.sub(/^:/, "") + ")"
        end
      end

      subs = "{%= #{segments.join} %}"
      buff << subs

      (original_line_length - subs.lines.size).times do
        buff << "\n{% %}" # preserve original line length
      end
    end
  end

  # Process any render directives
  string = buff
  buff = ""
  until string.empty?
    text, code, string = string.partition(/{%@([a-z_`]+)?(.*?)%}/m)

    buff << text
    if code.length > 0
      directive = $1
      code = $2
      unless ["end", ""].include? code.strip
        directive = $1 ? self.class.directives[$1] : self.class.directives["@"]

        if directive
          additional_length = "#{buff}#{code}".lines.size
          directive.(code, buff)
          (additional_length - buff.lines.size).times do
            buff << "{% %}\n" # preserve original directive line length
          end
        else
          raise "Handler for Serbea template directive `#{$1}' not found"
        end
      else
        buff << "{% end %}"
      end
    end
  end

  buff
end