Rake is a Make-inspired task-management utility that reads and executes tasks defined in a Rakefile, using Ruby syntax instead of Make syntax. section 1.4 section 1.4.3
An interactive cleanup task
A namespaced task can inspect /tmp, skip non-files, ask before deletion, delete entries after answers beginning with y, and stop on q. Run it with rake admin:clean_tmp. section 1.4.3
Rake tasks in this example combine ordinary Ruby mechanisms:
- Dir["/tmp/*"].each iterates through directory entries and binds each entry to a block parameter. section 1.4.3
- next unless File.file?(f) skips entries that are not files. section 1.4.3
- A case statement selects deletion or termination based on the user’s response. section 1.4.3
- desc documents a task and makes its purpose visible through rake --tasks. section 1.4.3
Listing 1.5 Rakefile defining clean_tmp tasks inside the admin namespace
namespace :admin do
desc "Interactively delete all files in /tmp"
task :clean_tmp do #1
Dir["/tmp/*"].each do |f| 1
next unless File.file?(f) 2
print "Delete #{f}? " 3
answer = $stdin.gets
case answer
when /^y/
File.delete(f) 4
when /^q/
break 5
end
end
end
end
Inspect the complete Rakefile defining the namespaced cleanup task. section 1.4.3
Namespaces organize task names: nesting clean inside admin produces admin:clean:tmp, making related operations easier to invoke and list. section 1.4.3
