{"id":1853,"date":"2010-11-18T04:16:39","date_gmt":"2010-11-18T03:16:39","guid":{"rendered":"http:\/\/www.devco.net\/?p=1853"},"modified":"2010-11-18T04:16:39","modified_gmt":"2010-11-18T03:16:39","slug":"a_few_rake_tips","status":"publish","type":"post","link":"https:\/\/www.devco.net\/archives\/2010\/11\/18\/a_few_rake_tips.php","title":{"rendered":"A few rake tips"},"content":{"rendered":"
Rake<\/a> is the Ruby make system, it lets you write tasks using the Ruby language and is used in most Ruby projects.<\/p>\n I wanted to automate some development tasks and had to figure out a few patterns, thought I’d blog them for my own future reference and hopefully to be useful to someone else.<\/p>\n In general people pass variables on the command line to rake, something like:<\/p>\n <\/code><\/p>\n This is ok if you know all the variables you can pass but sometimes it’s nice to support asking if something isn’t given:<\/p>\n <\/code><\/p>\n This will support running like:<\/p>\n <\/code><\/p>\n It will also though prompt for the information with a default if the environment variable isn’t set. The only real trick here is that you have to use STDIN.gets<\/em> and not just gets<\/em>. For added niceness you could use Highline<\/a> to build the prompts but that’s an extra dependency.<\/p>\n Here is what it does if you don’t specify a environment var:<\/p>\n <\/code><\/p>\n The second tip is about rendering templates, I am using the above ask method to ask a bunch of information from the user and then building a few templates based on that. So I am calling ERB a few times and wanted to write a helper. <\/p>\n <\/code><\/p>\n The template would just have:<\/p>\n<\/p>\n
\r\n$ ENVIRONMENT=production rake db::migrate\r\n<\/pre>\n
<\/p>\n
\r\ndef ask(prompt, env, default=\"\")\r\n return ENV[env] if ENV.include?(env)\r\n\r\n print \"#{prompt} (#{default}): \"\r\n resp = STDIN.gets.chomp\r\n\r\n resp.empty? ? default : resp\r\nend\r\n\r\ntask :do_something do\r\n what = ask(\"What should I do\", \"WHAT\", \"something\")\r\n puts \"Doing #{what}\"\r\nend\r\n<\/pre>\n
<\/p>\n
\r\n$ WHAT=\"foo\" rake do_something\r\n<\/pre>\n
<\/p>\n
\r\n$ rake do_something\r\n(in \/home\/rip\/temp)\r\nWhat should I do (something): test\r\nDoing test\r\n<\/pre>\n
<\/p>\n
\r\ndef render_template(template, output, scope)\r\n tmpl = File.read(template)\r\n erb = ERB.new(tmpl, 0, \"<>\")\r\n File.open(output, \"w\") do |f|\r\n f.puts erb.result(scope)\r\n end\r\nend\r\n\r\ntask :do_something do\r\n what = ask(\"What do you want to do\", \"WHAT\", \"something\")\r\n \r\n render_template(\"simple.erb\", \"\/tmp\/output.txt\", binding)\r\nend\r\n<\/pre>\n