lightbulb logo

Using Rake to build a site

I've been continuing to experiment with ruby. This morning I took a look at rake. It's ruby's equivalent of make and instead of writing a makefile you write a rakefile. What makes rakefiles powerful is that they are actually valid ruby programs. Rake is an example of a DSL, in this case embedded within the ruby language. Here's an example rakefile:

file 'hello.o' => 'hello.c' do |t|
  gcc 'hello.c'
end

It looks kind of like a makefile. But because it's just a ruby program, you can include general purpose ruby code whenever you need to. Here's an example:

TARGET_DIR = ENV["TARGET_DIR"]
def find_feed_prerequisites(dest_path, source_path)
  rss_file = File.new(source_path)
  begin
    rss_doc = REXML::Document.new(rss_file)
  ensure
    rss_file.close
  end
  source_dir = File.dirname(source_path)
  REXML::XPath.each(rss_doc, '/rss/channel/item/link') do |link|
    item_path = File.join(source_dir, link.text)
    Rake::FileTask.define_task(dest_path => item_path)
  end
end
   
find_feed_prerequisites("#{TARGET_DIR}/rss.xml", 'input/rss.xml')
task :build => "#{TARGET_DIR}/rss.xml"
file "#{TARGET_DIR}/rss.xml" => "input/rss.xml" do |t|
  build_feed(t.name, "input/rss.xml")
end

This example is the beginnings of the rakefile I will use to build my site. Eventually it will check all the sources out of subversion, apply the site template to all the pages, query the database for comments to append to each page, etc. So far all it does is open up my source rss feed, iterate over the feed items, pull the title and introductory paragraph from each referenced webpage and copy the resulting feed into the target directory.

I've got a lot of work to do before I can start using this system but it's fun.