Class: Booster::Template
- Inherits:
-
Tilt::Template
- Object
- Tilt::Template
- Booster::Template
- Defined in:
- lib/booster/template.rb
Overview
Tilt integration which pre-processes ‘.booster` files by wrapping them in a CommonJS-like closure and converts inline templates to JavaScript functions using the Handlebars compiler. While it is at it, it also does string interpolation on regular JavaScript strings.
Constant Summary collapse
- TEMPLATE_SECTION =
Regex for capturing sections of template code to be compiled to JavaScript
/@@\s*([A-Za-z0-9]*)\n(((?!@@).)*)/m
- STRING_INTERPOLATION =
Regex for capturing string interpolations STRING_INTERPOLATION = /(‘|“)(.*)#([sS]+?)/
/#\{([\s\S]+?)\}/
Class Method Summary collapse
-
.default_mime_type ⇒ Object
Processing Booster files result in plain JavaScript.
Instance Method Summary collapse
Class Method Details
.default_mime_type ⇒ Object
Processing Booster files result in plain JavaScript.
20 21 22 |
# File 'lib/booster/template.rb', line 20 def self.default_mime_type 'application/javascript' end |
Instance Method Details
#evaluate(scope, locals, &block) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/booster/template.rb', line 24 def evaluate(scope, locals, &block) # Replace template code with compiled JavaScript data.gsub!(TEMPLATE_SECTION) do "var #{$1} = Handlebars.template(#{Handlebars.precompile($2.strip!)});\n\n" end # Convert string interpolation to string concatenation with rudimentary # guessing of quote type ($1). Since the template functions compiled in the # previous step are just functions it is possible to use interpolations there # as well, even if Handlebars does not support them by default. This is not # recommended though although it works. data.gsub!(STRING_INTERPOLATION, '\' + (\1) + \'') # Indent the module content if in development mode for increased readability if (Rails.env == 'development') data.gsub!(/^(.)/, ' \1') end # Wrap the whole thing in a closure and register it as a module (https://gist.github.com/1153919) @output ||= "require.define({'#{ module_name(scope) }': function(exports, require, module) {#{data}}});\n" end |