Skip to content

Commit

Permalink
Add CoffeeScript template engine
Browse files Browse the repository at this point in the history
Caveats: Requires `coffee` binary which now requires nodejs
  • Loading branch information
josh committed Sep 9, 2010
1 parent 50cb223 commit c72fea7
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
59 changes: 59 additions & 0 deletions lib/tilt.rb
Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions test/tilt_coffeescripttemplate_test.rb
@@ -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.