Class: Mutton::HandlebarsTemplateConverter

Inherits:
Tilt::Template
  • Object
show all
Defined in:
lib/mutton/handlebars_template_converter.rb

Overview

convert hbs files into javascript for the asset pipeline

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_mime_typeObject



7
8
9
# File 'lib/mutton/handlebars_template_converter.rb', line 7

def self.default_mime_type
  'application/javascript'
end

Instance Method Details

#evaluate(scope, _locals, &_block) ⇒ Object

called by sprockets when compiling



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/mutton/handlebars_template_converter.rb', line 20

def evaluate(scope, _locals, &_block)
  timing = {}
  ActiveSupport::Notifications.instrument 'evaluate_asset.Mutton', timing do
    start_time = Time.zone.now
    # clients require precompiled templates for optimization
    precompiled_template = HandlebarsCompiler.pre_compile(data)
    end_precompile_time = Time.zone.now
    start_write_source = Time.zone.now
    source = write_source(precompiled_template, scope.logical_path, Mutton.template_namespace)
    end_time = Time.zone.now
    precompile_time = ((end_precompile_time - start_time) * 1000).round(0)
    source_time = ((end_time - start_write_source) * 1000).round(0)
    timing[:precompile_time] = precompile_time
    timing[:source_time] = source_time
    source
  end
end

#initialize_engineObject

no changes implemented



12
13
# File 'lib/mutton/handlebars_template_converter.rb', line 12

def initialize_engine
end

#prepareObject

no changes implemented



16
17
# File 'lib/mutton/handlebars_template_converter.rb', line 16

def prepare
end

#write_source(code, path, namespace) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/mutton/handlebars_template_converter.rb', line 38

def write_source(code, path, namespace)
  # drop the first bit of path to get rid of root directory
  paths = path.split('/')
  paths.delete_at(0)
  virtual_path = paths.join('/')
  write_template(namespace, virtual_path, code)
end

#write_template(namespace, virtual_path, source) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/mutton/handlebars_template_converter.rb', line 46

def write_template(namespace, virtual_path, source)
  javascript_code = <<CODE
(function() {
var template = Handlebars.template,
    templates = this.#{namespace} = this.#{namespace} || {};
templates['#{virtual_path}'] = template(
#{source}
);
Handlebars.partials = this.#{namespace};
})(this);
//best with a large serving of mutton
CODE
  javascript_code
end