I doing up a small web page containing only static files. But I still wanted the power of ruby for certain bits of generation and templating. If that sounds up your alley, gem install erubis and follow along…
First, a custom erubis builder to load up our environment so we can use our own class objects in the context. If you like you can just pass a yml file straight into erubis using the -f flag, but I wanted to do some processing of the data first, so:
require ‘erubis’
require ‘yaml’
require ‘lib/my_object’
# Load context
objects = YAML.load(File.open(‘data.yml‘))
context = {
:my_objects => objects
}
ARGV.each do |arg|
input = File.read(arg)
eruby = Erubis::Eruby.new(input)
puts eruby.evaluate(context)
end
A Rantfile:
import “autoclean”
gen Rule, /^build/[^.]+.(html|css)$/ => lambda { |t| [“#{t.gsub(’build/’, ’src/’)}.erb”]} do |t|
sys “ruby lib/erubis.rb #{t.source} > #{t.name}”
end
file “build/images” do |t|
sys “cp -R images build/”
end
task :build => %w(index.html main.css images).collect {|x| “build/#{x}”}
gen AutoClean, :clean
Then you can use FileSystemWatcher to automatically kick off your build when any source files change:
require “filesystemwatcher”
watcher = FileSystemWatcher.new()
watcher.addDirectory(“src”, “*.*”)
watcher.sleepTime = 1
watcher.start { |status,file|
print “#{file} changed, rebuilding…”
`rant build`
}
watcher.join()
Voila! Now you can even keep your static projects DRY. Sure beats copy and paste coding.