Skip to content

Instantly share code, notes, and snippets.

@daytonn
Created November 25, 2012 17:54
Show Gist options
  • Select an option

  • Save daytonn/4144556 to your computer and use it in GitHub Desktop.

Select an option

Save daytonn/4144556 to your computer and use it in GitHub Desktop.
Automatic ejs template compilation
<%= "#{Rails.application.class.parent_name}" %>.Templates = <%= templates %>;
require 'ejs'
require 'erb'
require 'listen'
require 'fileutils'
namespace :jst do
@assets_path = File.join(Rails.root, 'lib', 'assets')
@javascripts_path = File.join(Rails.root, 'app', 'assets', 'javascripts')
@templates_path = File.join(@javascripts_path, 'templates')
@erb_template = File.join(@assets_path, 'compiled_templates.erb')
@template_file = File.join(@javascripts_path, 'application', 'templates.js')
desc "Compile the javascript templates"
task :build => :environment do
begin
templates = templates_hash @templates_path
compiled_templates = ERB.new(File.read(@erb_template))
templates = template_string templates
File.open(@template_file, "w+") { |f| f << compiled_templates.result(binding) }
puts "#{@template_file.gsub(Rails.root.to_s, '')} was built successfully"
rescue Exception => e
puts "There was an error compiling the templates\n"
raise e
end
end
desc "Watch the templates for changes and compile automatically"
task :watch => :environment do
puts "Watching for js template changes. Press Ctrl+C to quit"
Listen.to(@templates_path, filter: /\.jst$/) do
Rake::Task["jst:build"].execute
end
end
def templates_hash(path, data = {}, namespace = nil)
Dir.foreach(path) do |entry|
next if entry =~ /^\.{1,2}$/
full_path = File.join(path, entry)
namespace = File.basename(entry, '.jst')
if File.directory?(full_path)
templates_hash(full_path, data[namespace] = {})
else
template_name = File.basename(entry, '.jst')
data[template_name] = EJS.compile(File.read(full_path))
end
end
data
end
def template_string(templates)
templates.to_s.gsub(/\=\>/, ': ').gsub(/\"function/, 'function').gsub(/\}\"/, '}')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment