Permalink
Browse files

Merge remote branch 'josh/coffeescript'

  • Loading branch information...
2 parents 638e1db + c72fea7 commit b37321955c755d7f33f4194ce082e72336998104 @rtomayko committed Sep 10, 2010
Showing with 84 additions and 0 deletions.
  1. +59 −0 lib/tilt.rb
  2. +25 −0 test/tilt_coffeescripttemplate_test.rb
View
@@ -589,6 +589,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 b373219

Please sign in to comment.