Rake Breathing New Life to Building Old Projects

I’ve seen lots of examples of rake (the ruby make replacement) being used as a build tool in non-ruby projects. Many of these are still modern platforms, like .Net. For example, StructureMap builds with rake. But I’ve found that even on older platforms, the power of having a full programming language in your build tool is useful.

Recently, I was working through examples in Thinking in C++, and there is the need to build many small one file examples. I started writing a Makefile to simplify this, and decided to try rake instead.

The power of a programming language brings a lot to table when doing repetitive tasks. Check out the following Rakefile which generates a build, run, and clean method for each file listed in an array. And there are aggregate methods which will run or clean all.

exe_name = ["hello","c_in_cpp","file","vector"]

exe_name.each do |f|
  desc "clean #{f}"
  task "clean_#{f}".to_sym do
    sh "rm -rf #{f} #{f}.o"
  end

  desc "build #{f}"
  task "build_#{f}".to_sym => "clean_#{f}" do
    sh "g++ #{f}.cpp -o #{f}"
  end

  desc "run #{f}"
  task "run_#{f}".to_sym => "build_#{f}" do
    sh "./#{f} 2> error.log"
  end
end

desc "run all"
task :default => exe_name.collect{|f| "run_#{f}"}

desc "clean all"
task :clean => exe_name.collect{|f| "clean_#{f}"}

If any of the above is unclear, and you want to see the output, do the following: copy and paste that code into a file named “Rakefile”. Run “rake -T” to lists all available tasks. You won’t be able to actually run the tasks, unless you have the appropriate cpp files in the directory (ie “rake run_hello” requires hello.cpp).

If you want to learn a build tool, and know ruby, or want to learn ruby rather than some specialized build language with no other uses, give rake a shot.