Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Created October 31, 2008 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmccray/21381 to your computer and use it in GitHub Desktop.
Save mattmccray/21381 to your computer and use it in GitHub Desktop.
desc "Compiles haml files (and hamlets) - v1.2"
task :hamlet do
# by M@
require 'rubygems'
require 'haml'
require 'fileutils'
main_files = []
@@src_path = File.expand_path( ENV.fetch('SRC', './') )
@@out_path = File.expand_path( ENV.fetch('OUT', './') )
@@cache = {}
# For better 'code'/pre support...
class Code
include Haml::Helpers
def initialize(text)
@text = text
end
def render
"<pre>#{preserve @text}</pre>"
end
end
# Javascript pass-through filter...
class Javascript
def initialize(script)
@script = script
end
def render
"<script type=\"text/javascript\">\n#{@script.chomp}\n</script>"
end
end
# Loads from file, or cache, and renders content as HAML
def render_hamlet(name, html, opts={})
@@src_path
haml_file = File.join(@@src_path, "_#{name}.haml" )
@@cache[name] = IO.readlines( haml_file ).join unless @@cache.has_key?( name )
haml_source = @@cache[name]
engine = Haml::Engine.new( haml_source,
:attr_wrapper=>'"',
:locals=>opts.merge({ :content=>html }),
:filename=>haml_file,
:filters=>{ 'javascript'=>Javascript,
'code' =>Code} )
engine.render
end
# Create hamlets... Heh
Dir.glob( "#{@@src_path}/*.haml" ).each do |haml_file|
if /_(\w*).haml/ =~ File.basename( haml_file )
hamlet_name = $1.chomp
eval <<-EOR
def #{hamlet_name}(opts={}, &block)
html = block_given? ? capture_haml(&block).to_s : ''
render_hamlet('#{hamlet_name}', html, opts)
end
EOR
else
main_files << haml_file
end
end
# Process all the files that don't start with _
main_files.each do |haml_file|
begin
source = IO.readlines(haml_file).join
engine = Haml::Engine.new( source,
:attr_wrapper=>'"',
:filename=>haml_file,
:filters=>{'javascript'=>Javascript,
'code' =>Code} )
html_file = File.expand_path( File.join(@@out_path, File.basename(haml_file).gsub('.haml', '.html')) )
FileUtils.mkdir_p( @@out_path ) unless File.exists?( @@out_path )
File.open( html_file, 'w') do |f|
f.write engine.render
puts " - Created #{html_file}"
end
rescue
puts " x Couldn't create html from #{haml_file}"
puts " #{$!}"
end
end
# Ze End
puts "Done."
end
task :default=>:hamlet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment