liveBook · Manning

Rake

As explained in The Well-Grounded Rubyist, Fourth Edition

Rake is a Ruby-based build utility that defines and runs task-based automation scripts.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains task definitions, descriptions, namespaces, invocation, iteration, filtering, prompting, and control flow through one worked cleanup task.
Examples
Uses an interactive /tmp cleanup task, admin namespaces, rake task listing, and nested names such as admin:clean:tmp.
What it assumes
Assumes some programming experience while teaching the required Ruby techniques through a concrete task.
What you can do after
Operate Rake by defining, documenting, listing, namespacing, and invoking Ruby-based automation tasks.
How it connects
Connects Rake with Ruby syntax, Make, namespaces, iterators, blocks, case statements, and command-line tools.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.