Class: Mustache::JavascriptGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/mustache/javascript_generator.rb

Instance Method Summary collapse

Constructor Details

#initializeJavascriptGenerator

Returns a new instance of JavascriptGenerator.



5
6
7
8
9
10
11
# File 'lib/mustache/javascript_generator.rb', line 5

def initialize
  @n        = 0
  @globals  = []
  @locals   = []
  @helpers  = {}
  @partials = {}
end

Instance Method Details

#compile(exp) ⇒ Object



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
# File 'lib/mustache/javascript_generator.rb', line 139

def compile(exp)
  main = global
  body = global

  compile_closure!(body, exp)

  helpers = self.helpers

  <<-JS.gsub("        ", "")
    (function() {
      #{globals.strip}
      #{helpers.strip}
      #{partials.strip}

      #{main} = function #{main}(obj) {
        var stack, out;
        stack = [];
        stack.push(obj);
        out = [];
        #{body}(stack, out);
        return out.join("");
      };

      return #{main};
    })()
  JS
end

#compile!(exp) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/mustache/javascript_generator.rb', line 167

def compile!(exp)
  case exp.first
  when :multi
    exp[1..-1].map { |e| compile!(e) }.join
  when :static
    str(exp[1])
  when :mustache
    send("on_#{exp[1]}", *exp[2..-1])
  else
    raise "Unhandled exp: #{exp.first}"
  end
end

#compile_closure!(name, tokens) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/mustache/javascript_generator.rb', line 242

def compile_closure!(name, tokens)
  @locals.push([])
  code = compile!(tokens)
  locals = self.locals
  @locals.pop

  @partials[name] = <<-JS
    #{name} = function #{name}(stack, out) {
      #{locals.strip}
      #{code.strip}
    };
  JS

  nil
end

#global(name = nil) ⇒ Object



313
314
315
316
317
318
319
320
321
322
323
# File 'lib/mustache/javascript_generator.rb', line 313

def global(name = nil)
  if name
    @globals << name.to_sym
    name
  else
    @n += 1
    name = :"g#{@n}"
    @globals << name
    name
  end
end

#globalsObject



119
120
121
122
123
124
125
# File 'lib/mustache/javascript_generator.rb', line 119

def globals
  if @globals.any?
    "var #{@globals.join(', ')};\n"
  else
    ""
  end
end

#helpersObject



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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
# File 'lib/mustache/javascript_generator.rb', line 13

def helpers
  out = ""

  if @helpers[:fetch]
    global :fetch
    out << <<-JS
      fetch = function fetch(stack, key) {
        var i, v;
        for (i = stack.length - 1; i >= 0; i -= 1) {
          v = stack[i][key];
          if (v) {
            return v;
          }
        }
      };
    JS
  end

  if @helpers[:escape]
    global :escape
    out << <<-JS
      escape = function escape(value) {
        return ('' + value)
          .replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;')
          .replace(/\x22/g, '&quot;');
      };
    JS
  end

  if @helpers[:isEmpty]
    @helpers[:isArray] = @helpers[:isObject] = true
    global :isEmpty
    out << <<-JS
      isEmpty = function isEmpty(obj) {
        var key;

        if (!obj) {
          return true;
        } else if (isArray(obj)) {
          return obj.length === 0;
        } else if (isObject(obj)) {
          for (key in obj) {
            if (obj.hasOwnProperty(key)) {
              return false;
            }
          }
          return true;
        } else {
          return false;
        }
      };
    JS
  end

  if @helpers[:isArray]
    global :isArray
    out << <<-JS
      isArray = Array.isArray || function (obj) {
        return Object.prototype.toString.call(obj) === '[object Array]';
      };
    JS
  end

  if @helpers[:isObject]
    global :isObject
    out << <<-JS
      isObject = function isObject(obj) {
        return (obj && typeof obj === 'object');
      };
    JS
  end

  if @helpers[:isFunction]
    global :isFunction
    out << <<-JS
      isFunction = function isFunction(obj) {
        return !!(obj && obj.constructor && obj.call && obj.apply);
      };
    JS
  end

  if @helpers[:reduce]
    global :reduce
    out << <<-JS
      reduce = Array.prototype.reduce || function (iterator, memo) {
        var i;
        for (i = 0; i < this.length; i++) {
          memo = iterator(memo, this[i]);
        }
        return memo;
      };
    JS

    global :traverse
    out << <<-JS
      traverse = function traverse(value, key) {
        return value && value[key];
      };
    JS
  end

  out.gsub("          ", "")
end

#local(name = nil) ⇒ Object



325
326
327
328
329
# File 'lib/mustache/javascript_generator.rb', line 325

def local(name = nil)
  raise "not in closure" unless @locals.last
  @locals.last << name.to_sym
  name
end

#localsObject



127
128
129
130
131
132
133
# File 'lib/mustache/javascript_generator.rb', line 127

def locals
  if @locals.last.any?
    "var #{@locals.last.join(', ')};\n"
  else
    ""
  end
end

#on_etag(name) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'lib/mustache/javascript_generator.rb', line 275

def on_etag(name)
  @helpers[:isFunction] = true
  @helpers[:isEmpty] = @helpers[:escape] = true

  v = local(:v)

  <<-JS
    #{v} = #{compile!(name).strip};
    if (isFunction(#{v})) {
      #{v} = #{v}.call(stack[stack.length - 1]);
    }
    if (!isEmpty(#{v})) {
      out.push(escape(#{v}));
    }
  JS
end

#on_fetch(names) ⇒ Object



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/mustache/javascript_generator.rb', line 292

def on_fetch(names)
  @helpers[:fetch] = true

  names = names.map { |n| n.to_s }

  case names.length
  when 0
    "stack[stack.length-1]"
  when 1
    "fetch(stack, #{names.first.inspect})"
  else
    @helpers[:reduce] = true
    initial, *rest = names
    "reduce.call(#{rest.inspect}, traverse, fetch(stack, #{initial.inspect}))"
  end
end

#on_inverted_section(name, content, raw, _) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/mustache/javascript_generator.rb', line 214

def on_inverted_section(name, content, raw, _)
  @helpers[:isEmpty] = true

  f, v = global, local(:v)

  compile_closure!(f, content)

  <<-JS
    #{v} = #{compile!(name).strip};
    if (isEmpty(#{v})) {
      #{f}(stack, out);
    }
  JS
end

#on_partial(name, indentation) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/mustache/javascript_generator.rb', line 229

def on_partial(name, indentation)
  unless @partials[name]
    @partials[name] = true # Stub for recursion

    source   = Mustache.partial(name).to_s.gsub(/^/, indentation)
    template = Mustache.templateify(source)

    compile_closure!(name, template.tokens)
  end

  "#{name}(stack, out);\n"
end

#on_section(name, content, raw, delims) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/mustache/javascript_generator.rb', line 180

def on_section(name, content, raw, delims)
  @helpers[:isEmpty] = true
  @helpers[:isObject] = @helpers[:isArray] = @helpers[:isFunction] = true

  f, v, i = global, local(:v), local(:i)

  compile_closure!(f, content)

  <<-JS
    #{v} = #{compile!(name).strip};
    if (!isEmpty(#{v})) {
      if (isFunction(#{v})) {
        out.push(#{v}.call(stack[stack.length - 1], function () {
          var out = [];
          #{f}(stack, out);
          return out.join("");
        }));
      } else if (isArray(#{v})) {
        for (#{i} = 0; #{i} < #{v}.length; #{i} += 1) {
          stack.push(#{v}[#{i}]);
          #{f}(stack, out);
          stack.pop();
        }
      } else if (isObject(#{v})) {
        stack.push(#{v});
        #{f}(stack, out);
        stack.pop();
      } else {
        #{f}(stack, out);
      }
    }
  JS
end

#on_utag(name) ⇒ Object



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/mustache/javascript_generator.rb', line 258

def on_utag(name)
  @helpers[:isFunction] = true
  @helpers[:isEmpty] = true

  v = local(:v)

  <<-JS
    #{v} = #{compile!(name).strip};
    if (isFunction(#{v})) {
      #{v} = #{v}.call(stack[stack.length - 1]);
    }
    if (!isEmpty(#{v})) {
      out.push(#{v});
    }
  JS
end

#partialsObject



135
136
137
# File 'lib/mustache/javascript_generator.rb', line 135

def partials
  @partials.values.join("\n")
end

#str(s) ⇒ Object



309
310
311
# File 'lib/mustache/javascript_generator.rb', line 309

def str(s)
  "out.push(#{s.inspect});\n"
end