Class: Rake::Pipeline::Web::Filters::HandlebarsFilter

Inherits:
Filter
  • Object
show all
Includes:
FilterWithDependencies
Defined in:
lib/rake-pipeline-web-filters/handlebars_filter.rb

Overview

A filter that converts handlebars templates to javascript and stores them in a defined variable.

Examples:

Rake::Pipeline.build do
  input "**/*.handlebars"
  output "public"

  # Compile each handlebars file to JS
  handlebars
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &block) ⇒ HandlebarsFilter

Returns a new instance of HandlebarsFilter

Options Hash (options):

  • :target (Array)

    the variable to store templates in

  • :compile_open (Array)

    the js to wrap template contents in

  • :compile_close (Array)

    the js to wrap template contents in


31
32
33
34
35
36
37
38
39
40
# File 'lib/rake-pipeline-web-filters/handlebars_filter.rb', line 31

def initialize(options={},&block)
  # Convert .handlebars file extensions to .js
  block ||= proc { |input| input.sub(/\.handlebars|\.hbs$/, '.js') }
  super(&block)
  @options = {
      :target =>'Ember.TEMPLATES',
      :wrapper_proc => proc { |source| "Ember.Handlebars.compile(#{source});" },
      :key_name_proc => proc { |input| File.basename(input.path, File.extname(input.path)) }
    }.merge(options)
end

Instance Attribute Details

#optionsHash (readonly)


19
20
21
# File 'lib/rake-pipeline-web-filters/handlebars_filter.rb', line 19

def options
  @options
end

Instance Method Details

#generate_output(inputs, output) ⇒ Object


42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rake-pipeline-web-filters/handlebars_filter.rb', line 42

def generate_output(inputs, output)

  inputs.each do |input|
    # The name of the template is the filename, sans extension
    name = options[:key_name_proc].call(input)

    # Read the file and escape it so it's a valid JS string
    source = input.read.to_json

    # Write out a JS file, saved to target, wrapped in compiler
    output.write "#{options[:target]}['#{name}']=#{options[:wrapper_proc].call(source)}"
  end
end