Rake Rocky II

Last time we started looking at Rake. Today, we’ll finish our Rakefile.

Recall that we were working on an ActionScript project. The our first target was an XML configuration file. Our next target is using swfmill to turn that XML file into a Flash .swf. The Ruby code is simple as can be:

file 'resources/images.swf' => 'resources/images.xml' do
  sh %{swfmill simple resources/images.xml resources/images.swf}
end

We state our dependency and then we call swfmill. Recall that %{string literal} is just another way to write “string literal” in Ruby.

Now we want to use MTASC to bake-in our scripts. We define our script files, include the images swf, and define our file target which calls MTASC:

SCRIPTS = FileList['src/*.as']
SCRIPTS.include 'resources/images.swf'
FINAL_SWF = "#{PROJECT_NAME}.swf" 
file FINAL_SWF => SCRIPTS do |t|
  sh %{mtasc -cp src -trace Logger.trace -swf resources/images.swf -out #{t.name} -main Main.as}
end

Notice that this time I used a block argument t to refer back to the target FINAL_SWF.

Our final task is to make a project specific HTML file from a template. For our template, we use expressions of the form ###PROJECT_NAME### to denote parts that should be filled in. If we needed something fancy, we could use RHTML templates like Rails does, but this isn’t fancy, so we to the string replacement ourselves:

HTML = "#{PROJECT_NAME}.html" 
file HTML => [FINAL_SWF, 'resources/template.html'] do |t|
  open HTML, 'w' do |file|
    html = IO.read 'resources/template.html'
    html.gsub! /###([^#]+)###/ do
      self.class.const_get $1.to_sym
    end
    file.puts html 
  end
end

The gsub! is the meaty line. The call html.gsub! says to do in place regular expression substitution. The pattern /###([^#]+)###/ matcher our template markup. Then the block explains what to do with the match. Now $1 refers to the parenthesized part of the match and to_sym converts it from a string to a symbol. We use self.class.const_get to lookup the symbol and return the value as what we want to replace in the template.

That’s basically it for the Rakefile. Throughout we leveraged the fact that Rake is a domain specific language built on top of Ruby to use plain Ruby instead of calling external tools. Next time we see what happens when the Ant attacks!