Permalink
Browse files

Add CoffeeScript template engine

Caveats: Requires `coffee` binary which now requires nodejs
  • Loading branch information...
1 parent 50cb223 commit c72fea71a45ea0ff6342ea2b38d5f427be3782b4 @josh josh committed Sep 9, 2010
Showing with 84 additions and 0 deletions.
  1. +59 −0 lib/tilt.rb
  2. +25 −0 test/tilt_coffeescripttemplate_test.rb
View
@@ -568,6 +568,65 @@ def evaluate(scope, locals, &block)
register 'less', LessTemplate
+ # CoffeeScript template implementation. See:
+ # http://coffeescript.org/
+ #
+ # CoffeeScript templates do not support object scopes, locals, or yield.
+ #
+ # Requires `coffee` binary be in PATH or specified with `coffee_bin`.
+ class CoffeeScriptTemplate < Template
+ @@coffee_bin = nil
+ @@default_nowrap = true
+
+ def self.locate_coffee_bin
+ out = `which coffee`
+ if $?.success?
+ out.chomp
+ else
+ raise LoadError, "could not find `coffee` in PATH"
+ end
+ end
+
+ def self.coffee_bin
+ @@coffee_bin ||= locate_coffee_bin
+ end
+
+ def self.coffee_bin=(path)
+ @@coffee_bin = path
+ end
+
+ def self.default_nowrap
+ @@default_nowrap
+ end
+
+ def self.default_nowrap=(value)
+ @@default_nowrap = value
+ end
+
+ def prepare
+ @nowrap = options.key?(:nowrap) ? options[:nowrap] :
+ self.class.default_nowrap
+ end
+
+ def evaluate(scope, locals, &block)
+ @output ||= coffee(data)
+ end
+
+ private
+ def coffee(input)
+ command = "#{self.class.coffee_bin} -sp"
+ command += " --no-wrap" if @nowrap
+
+ IO.popen(command, "w+") do |f|
+ f << input
+ f.close_write
+ f.read
+ end
+ end
+ end
+ register 'coffee', CoffeeScriptTemplate
+
+
# Nokogiri template implementation. See:
# http://nokogiri.org/
class NokogiriTemplate < Template
@@ -0,0 +1,25 @@
+require 'contest'
+require 'tilt'
+
+begin
+ Tilt::CoffeeScriptTemplate.locate_coffee_bin
+
+ class CoffeeScriptTemplateTest < Test::Unit::TestCase
+ test "is registered for '.coffee' files" do
+ assert_equal Tilt::CoffeeScriptTemplate, Tilt['test.coffee']
+ end
+
+ test "compiles and evaluates the template on #render" do
+ template = Tilt::CoffeeScriptTemplate.new { |t| "puts 'Hello, World!'\n" }
+ assert_equal "puts('Hello, World!');", template.render
+ end
+
+ test "enabling coffee-script wrapper" do
+ template = Tilt::CoffeeScriptTemplate.new(:nowrap => false) { |t| "puts 'Hello, World!'\n" }
+ assert_equal "(function() {\n puts('Hello, World!');\n})();\n", template.render
+ end
+ end
+
+rescue LoadError => boom
+ warn "Tilt::CoffeeScriptTemplate (disabled)\n"
+end

0 comments on commit c72fea7

Please sign in to comment.