Scroll to top
This post is part of a series called All About Rake.
Rake 201

This article explains the basics of Rake. It’s a super popular build tool that is written in Ruby. It offers a lot of flexibility and is used to manage all kinds of tasks. If you are using Rails, I recommend taking a look under the hood to find out what tasks are at your disposal and how to write your own.

Topics

  • What Is Rake?
  • Task List
  • Getting Started
  • Namespaces
  • Prerequisites
  • Passing Arguments
  • Tasks of Interest

What Is Rake?

Thanks to Rails, Rake has become a de facto standard as a Ruby build tool. It’s super popular in the Ruby community. Very early, the team behind Rails decided to use Rake as the builder for Rails itself, which meant that in the past when you downloaded Rails, you also needed a copy of Rake. That way it exposed Rake to a lot of people. A little later, it was included into Ruby (1.9) itself.

Rake de facto replaced the Unix utility Make as a build tool in Ruby land. A build tool like Rake is handy for automating tasks of various kinds—a software for managing tasks basically. It is often used for administration tasks in Rails—which is where you most likely have run into it so far—but its use cases are plenty. Some people write their ebooks in Markdown and have set up Rake tasks that convert the relevant files to intermediate HTML files, which then in turn get converted into ebook formats, for example. Saves a lot of trouble to use Rake for that.

What makes Rake really powerful is that these tasks can relate to one another and can be built on top of each other. Also, since it is written in Ruby, you can write any Ruby code for your tasks. Want to use Ruby libraries in your Rake tasks? No problem! Fun fact: it is the most downloaded RubyGem, with over 100 million downloads. So definitely something in your tool belt that you should pay a little more attention to. 

It was conceived by the late Jim Weirich, a well-known and beloved developer, speaker and contributor to the Ruby ecosystem. It’s a beautiful tool really—thanks, Jim! RIP!

Task List

Let’s take a look at some tasks that Rails offers right out of the box. I bet you are a bit surprised at what’s available if you haven’t checked before. In the relevant directory of your app or your Rakefile, you can list them by typing the following into a shell:

1
rake --tasks
2
3
#or
4
5
rake -T

Output:

1
rake about                              # List versions of all Rails frameworks and the environment
2
rake assets:clean[keep]                 # Remove old compiled assets
3
rake assets:clobber                     # Remove compiled assets
4
rake assets:environment                 # Load asset compile environment
5
rake assets:precompile                  # Compile all the assets named in config.assets.precompile
6
rake cache_digests:dependencies         # Lookup first-level dependencies for TEMPLATE (like messages/show or comm...
7
rake cache_digests:nested_dependencies  # Lookup nested dependencies for TEMPLATE (like messages/show or comments/...
8
rake db:create                          # Creates the database from DATABASE_URL or config/database.yml for the cu...
9
rake db:drop                            # Drops the database from DATABASE_URL or config/database.yml for the curr...
10
rake db:fixtures:load                   # Load fixtures into the current environment's database
11
rake db:migrate                         # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
12
rake db:migrate:status                  # Display status of migrations
13
rake db:rollback                        # Rolls the schema back to the previous version (specify steps w/ STEP=n)
14
rake db:schema:cache:clear              # Clear a db/schema_cache.dump file
15
rake db:schema:cache:dump               # Create a db/schema_cache.dump file
16
rake db:schema:dump                     # Create a db/schema.rb file that is portable against any DB supported by AR
17
rake db:schema:load                     # Load a schema.rb file into the database
18
rake db:seed                            # Load the seed data from db/seeds.rb
19
rake db:setup                           # Create the database, load the schema, and initialize with the seed data ...
20
rake db:structure:dump                  # Dump the database structure to db/structure.sql
21
rake db:structure:load                  # Recreate the databases from the structure.sql file
22
rake db:version                         # Retrieves the current schema version number
23
rake doc:app                            # Generate docs for the app -- also available doc:rails, doc:guides (optio...
24
rake log:clear                          # Truncates all *.log files in log/ to zero bytes (specify which logs with...
25
rake middleware                         # Prints out your Rack middleware stack
26
rake notes                              # Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)
27
rake notes:custom                       # Enumerate a custom annotation, specify with ANNOTATION=CUSTOM
28
rake rails:template                     # Applies the template supplied by LOCATION=(/path/to/template) or URL
29
rake rails:update                       # Update configs and some other initially generated files (or use just upd...
30
rake routes                             # Print out all defined routes in match order, with names
31
rake secret                             # Generate a cryptographically secure secret key (this is typically used t...
32
rake spec                               # Run all specs in spec directory (excluding plugin specs)
33
rake spec:controllers                   # Run the code examples in spec/controllers
34
rake spec:features                      # Run the code examples in spec/features
35
rake spec:helpers                       # Run the code examples in spec/helpers
36
rake spec:models                        # Run the code examples in spec/models
37
rake spec:views                         # Run the code examples in spec/views
38
rake stats                              # Report code statistics (KLOCs, etc) from the application or engine
39
rake time:zones:all                     # Displays all time zones, also available: time:zones:us, time:zones:local...
40
rake tmp:clear                          # Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions...
41
rake tmp:create                         # Creates tmp directories for sessions, cache, sockets, and pids

The output in a Rails app is surprisingly plentiful, isn’t it? You can find a lot more handy tasks than the usual rake db:migrate or rake routes that we are so familiar with and run multiple times on a daily basis. 

On the left, you see the various tasks, and on the right, you see what is optionally provided as a description to every rake task. If you want to see the complete list, which among other things also includes tasks that lack a description, you need to add an additional flag.

Shell:

1
rake -T -A
2
3
#or
4
5
rake -T -all

Output:

1
rake about                              # List versions of all Rails frameworks and the environment
2
rake assets:clean[keep]                 # Remove old compiled assets
3
rake assets:clobber                     # Remove compiled assets
4
rake assets:environment                 # Load asset compile environment
5
rake assets:precompile                  # Compile all the assets named in config.assets.precompile
6
rake cache_digests:dependencies         # Lookup first-level dependencies for TEMPLATE (like messages/show or comments/_comment.html)
7
rake cache_digests:nested_dependencies  # Lookup nested dependencies for TEMPLATE (like messages/show or comments/_comment.html)
8
rake db:_dump                           # 
9
rake db:abort_if_pending_migrations     # 
10
rake db:charset                         # 
11
rake db:collation                       # 
12
rake db:create                          # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databases in the config)
13
rake db:create:all                      # 
14
rake db:drop                            # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config)
15
rake db:drop:all                        # 
16
rake db:fixtures:identify               # 
17
rake db:fixtures:load                   # Load fixtures into the current environment's database
18
rake db:forward                         # 
19
rake db:load_config                     # 
20
rake db:migrate                         # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
21
rake db:migrate:down                    # 
22
rake db:migrate:redo                    # 
23
rake db:migrate:reset                   # 
24
rake db:migrate:status                  # Display status of migrations
25
rake db:migrate:up                      # 
26
rake db:purge                           # 
27
rake db:purge:all                       # 
28
rake db:reset                           # 
29
rake db:rollback                        # Rolls the schema back to the previous version (specify steps w/ STEP=n)
30
rake db:schema:cache:clear              # Clear a db/schema_cache.dump file
31
rake db:schema:cache:dump               # Create a db/schema_cache.dump file
32
rake db:schema:dump                     # Create a db/schema.rb file that is portable against any DB supported by AR
33
rake db:schema:load                     # Load a schema.rb file into the database
34
rake db:schema:load_if_ruby             # 
35
rake db:seed                            # Load the seed data from db/seeds.rb
36
rake db:setup                           # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the database first)
37
rake db:structure:dump                  # Dump the database structure to db/structure.sql
38
rake db:structure:load                  # Recreate the databases from the structure.sql file
39
rake db:structure:load_if_sql           # 
40
rake db:test:clone                      # 
41
rake db:test:clone_schema               # 
42
rake db:test:clone_structure            # 
43
rake db:test:deprecated                 # 
44
rake db:test:load                       # 
45
rake db:test:load_schema                # 
46
rake db:test:load_structure             # 
47
rake db:test:prepare                    # 
48
rake db:test:purge                      # 
49
rake db:version                         # Retrieves the current schema version number
50
rake default                            # 
51
rake doc                                # 
52
rake doc/app                            # 
53
rake doc/app/created.rid                # 
54
rake doc:app                            # Generate docs for the app -- also available doc:rails, doc:guides (options: TEMPLATE=/rdoc-template.rb, TITLE="Custom Title")
55
rake doc:clobber                        # 
56
rake doc:clobber_app                    # 
57
rake doc:clobber_rails                  # 
58
rake doc:guides                         # 
59
rake doc:rails                          # 
60
rake doc:reapp                          # 
61
rake doc:rerails                        # 
62
rake environment                        # 
63
rake html                               # 
64
rake html/created.rid                   # 
65
rake log:clear                          # Truncates all *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)
66
rake magic                              # Magic rake task
67
rake middleware                         # Prints out your Rack middleware stack
68
rake no_description                     # 
69
rake notes                              # Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)
70
rake notes:custom                       # Enumerate a custom annotation, specify with ANNOTATION=CUSTOM
71
rake notes:fixme                        # 
72
rake notes:optimize                     # 
73
rake notes:todo                         # 
74
rake rails:template                     # Applies the template supplied by LOCATION=(/path/to/template) or URL
75
rake rails:templates:copy               # 
76
rake rails:update                       # Update configs and some other initially generated files (or use just update:configs or update:bin)
77
rake rails:update:bin                   # 
78
rake rails:update:configs               # 
79
rake railties:install:migrations        # 
80
rake routes                             # Print out all defined routes in match order, with names
81
rake secret                             # Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions)
82
rake spec                               # Run all specs in spec directory (excluding plugin specs)
83
rake spec:controllers                   # Run the code examples in spec/controllers
84
rake spec:features                      # Run the code examples in spec/features
85
rake spec:helpers                       # Run the code examples in spec/helpers
86
rake spec:models                        # Run the code examples in spec/models
87
rake spec:prepare                       # 
88
rake spec:statsetup                     # 
89
rake spec:views                         # Run the code examples in spec/views
90
rake stats                              # Report code statistics (KLOCs, etc) from the application or engine
91
rake time:zones:all                     # Displays all time zones, also available: time:zones:us, time:zones:local -- filter with OFFSET parameter, e.g., OFFSET=-6
92
rake time:zones:local                   # 
93
rake time:zones:us                      # 
94
rake tmp                                # 
95
rake tmp/cache                          # 
96
rake tmp/cache/assets                   # 
97
rake tmp/cache/assets/development       # 
98
rake tmp/cache/assets/production        # 
99
rake tmp/cache/assets/test              # 
100
rake tmp/pids                           # 
101
rake tmp/sessions                       # 
102
rake tmp/sockets                        # 
103
rake tmp:cache:clear                    # 
104
rake tmp:clear                          # Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:sockets:clear)
105
rake tmp:create                         # Creates tmp directories for sessions, cache, sockets, and pids
106
rake tmp:pids:clear                     # 
107
rake tmp:sessions:clear                 # 
108
rake tmp:sockets:clear                  # 

Surprise, almost three times as much! Take a look at them and play around if you like, but commit the highlights to memory for later usage in the future. Checking the tasks to see what’s available might prevent you from reinventing the wheel.

Getting Started

A Rakefile can have one of the following five appearances:

  • rakefile.rb
  • rakefile 
  • Rakefile
  • Rakefile.rb
  • .rake files

Mostly you will see the plain Rakefile version, but a framework like Rails needs more complex organization. Use whatever gets your blood flowing. You start by creating a Rakefile or files with a .rake extension if you want to split tasks up logically over multiple files. Then define your tasks inside either of them.

Custom Rakefile Organization

Rails makes this incredibly easy. It has a Rakefile in the root of your app. It contains the following:

Rakefile

1
require File.expand_path('../config/application', __FILE__)
2
3
Rails.application.load_tasks

When you have a lot of custom tasks, it makes more sense to split them into discrete .rake files and place them in lib/tasks. The Rakefile above just loads them, but the lib directory is a better logical home for the tasks. There is even a Rails generator to automate part of the process. If you type:

Shell

1
rails generate some_task
2
3
=> create lib/tasks/some_task.rake

You will get a Rakefile placed automatically in the right directory. Even the task is already set up for you. Nice! In other projects, not using Rails, you just need to create a rakelib directory and place your Rakefiles in there—preferably with .rake file extensions. Then create a file called Rakefile and all these files are already at your disposal.

Rake Task Anatomy

lib/tasks/some_task.rake

1
desc 'List versions of all Rails frameworks and the environment'
2
task :about do
3
  puts 'Some magic goes in here…'
4
end

For the complete Ruby newbies among you, and for people coming from bracket-heavy languages, this is how it would look with parentheses.

1
desc('List versions of all Rails frameworks and the environment')
2
task(:about) do
3
  puts('Some magic goes in here…')
4
end

Looks very weird, by the way. Just lose the extra parentheses—nobody writes tasks this way.

We provided a named task :about with a description that not only reminds us in the future what we wanted to achieve with particular tasks, but also shows up when we run rake -T. Don’t get lazy on this part; it’s probably not worth it.

Right below is the keyword task that defines a new task named about. This can be invoked on the command line via rake about which does its magic then. rake :about on the other hand will cause Rake to abort, not knowing “how to build task :about”.

Via the do end block, we have a lambda, and its body specifies what the task does. This is the basic setup a task will need. It offers a lot more options, of course, but the overall structure is the same. 

require / import

Some Rakefile

1
require './whatever.rb'

If you need to include other Ruby files or Rakefiles, it can easily be achieved by a standard require statement.

Some Rakefile

1
import 'whatever.rb'

Rake itself provides us with another way to do this—the import method. This can be used in any line of the Rakefile. This one will help when you run into trouble because the required file was loaded before the Rakefile finished loading and blew up therefore. The imported file, on the other hand, will always load after the Rakefile.

invoke & execute

Sometimes you might want to execute some defined task from your Task class manually. For this purpose, you have two methods of the Rake::Task class: execute and invoke.

1
Rake::Task['some_task'].invoke
2
Rake::Task['some_task'].execute

With the Rake::Task['some_task'] code, we got the some_task Rake task to execute. It returns an instance of the Rake::Task class and then runs any method on it that is available.

Namespaces

A very cool feature is the ability to namespace your tasks. You probably have used this dozens of times already. When you run rake db:migrate, you have made use of the db namespace, for example. You invoke the task by separating it with a colon : from the namespace. Namespaces are a handy way to organize your tasks within in a rake file—it keeps them logically separated. Multiple namespaces like rake time:zones:all are fine, by the way.

Other examples include:

1
rake db:drop 
2
rake db:seed
3
rake log:clear
4
rake spec:views
5
rake spec:models  
6
rake db:rollback
7
rake spec:helpers 
8
rake spec:features
9
rake db:schema:load  
10
rake assets:precompile 
11
rake db:migrate:status

Some Rakefile

1
namespace :db do
2
  desc 'Migrating some stuff'
3
  task :migrate do
4
    ...
5
  end
6
end

This is the basic setup. In reality it’s much more complicated and can even be nested multiple times. Have a quick peek at the Rails codebase and see for yourself how rake db:migrate is implemented. Don’t feel bad if it’s over your head. Just look around, try to discern how it’s structured, and move on for now.

Prerequisites

Another strategy to organize your tasks and to keep them DRY is using prerequisites for executing a task. It’s like a dependency that has to run first before the actual task starts its job. That way you can build up more complex tasks—as complex as you need. But I would recommend not getting too clever and to keep it as simple as possible—and as easy to understand as possible as well.

Some Rakefile

1
task :stop_megalomaniac do
2
  puts 'Lots of smart talk, car chases and guns fired'
3
end
4
5
task :bond_saves_the_day => :stop_psychotic_megalomaniac do
6
  puts 'Lots of Dom Pérignon, oysters and bond girl business'
7
end

If you want to rely on multiple tasks, you just stick them into an array. The order in which you place them matters, of course.

1
task :get_mr_wolf do
2
  puts "You ain’t got no problem Jules, I’m on it! Go in there and chill them out and wait for the wolf who should be coming directly!"
3
end
4
5
task :figure_out_bonnie_situation do
6
  puts "If I was informed correctly, the clock is ticking. Is that right Jimmy?"
7
end
8
9
task :calm_down_jimmy do
10
  puts "Jimmy, do me a favor, will you? I smelled some coffee back there. Would you make me a cup?"
11
end
12
13
task :get_vince_vega_in_line do
14
  puts "Come again? Get it straight buster. I’m not here to say please! I’m here to tell you what to do!"
15
end
16
17
task :clean_car do
18
  puts "I need you two fellas to take those cleaning products and clean the inside of the car. I’m talking fast, fast, fast!"
19
end
20
21
task :clean_crew do
22
  puts "Jim, the soap! O.K. gentlemen, you both been to county before I’m sure. Here it comes!"
23
end
24
25
task :get_rid_of_evidence_at_monster_joes do
26
  puts "So what’s with the outfits? You guys are going to a Volleyball game or something?"
27
end
28
29
task :drive_into_the_sunrise do
30
  puts "Call me Winston!"
31
end
32
33
task :solve_bonnie_situation => [:get_mr_wolf, :calm_down_jimmy, :figure_out_bonnie_situation, :get_vince_vega_in_line, :clean_car, :clean_crew, :get_rid_of_evidence_at_monster_joes, :drive_into_the_sunrise]  do
34
  puts "You know, I’d go for breakfast. Feel like having breakfast with me?"
35
end

If you run the rake task that depends on the other, we’ll get the following output:

Shell

1
$ rake solve_bonnie_situation
2
You ain’t got no problem Jules, I’m on it! Go in there and chill them out and wait for the wolf who should be coming directly!
3
Jimmy, do me a favor, will you? I smelled some coffee back there. Would you make me a cup?
4
If I was informed correctly, the clock is ticking. Is that right Jimmy?
5
Come again? Get it straight buster. I’m not here to say please! I’m here to tell you what to do!
6
I need you two fellas to take those cleaning products and clean the inside of the car. I’m talking fast, fast, fast!
7
Jim, the soap! O.K. gentlemen, you both been to county before I’m sure. Here it comes! 
8
So what’s with the outfits? You guys are going to a Volleyball game or something?
9
Call me Winston!
10
You know, I’d go for breakfast. Feel like having breakfast with me?

The order in which you define your rake tasks has no effect on the output—only the order in which you place the prerequisite tasks in the array for task dependencies. Also, please use the hashrocket => syntax for this.

A long list of dependencies might be a code smell. If you have to deal with something long, clean it up by encapsulating it inside a method which we then pass as a prerequisite.

1
def mr_wolf_tasks 
2
  [:get_mr_wolf, :calm_down_jimmy, :figure_out_bonnie_situation, :get_vince_vega_in_line, :clean_car, :clean_crew, :get_rid_of_evidence_at_monster_joes, :drive_into_the_sunrise] 
3
end
4
5
...
6
7
task :solve_bonnie_situation => mr_wolf_tasks do
8
  puts 'You know, I’d go for breakfast. Feel like having breakfast with me?'
9
end

In the context of prerequisites, one thing to keep in mind is that you only need to mention a namespace if you are outside the relevant one.

Some Rakefile

1
namespace :marsellus_wallace do
2
  task :call_winston_wolf do
3
    ...
4
  end
5
end
6
7
task :solve_bonnie_situation => 'marsellus_wallace:call_winston_wolf' do
8
  ...
9
end
10
11
namespace :marsellus_wallace do
12
  task :call_winston_wolf do
13
    ...
14
  end
15
16
  task :solve_bonnie_situation => :call_winston_wolf do
17
    ...
18
  end
19
end

Important to note, though: in case you do need to mention the namespace, you have to pass the prerequisite as a string => 'marsellus_wallace:call_winston_wolf'.

Of course, the examples above are goofy and not real-life examples, but the intention was to show you how prerequisites work and how you’d put them together while they depend on each other.

Passing Arguments

You have two options to pass arguments to Rake tasks: either by using Bash variables or by making use of Rake’s syntax itself.

ENV Variable

In case you haven’t played with Bash before—or Bash sounds like gobbledegook to you—let’s take five and start from the beginning. Bash in your shell offers two sorts of variables: global (aka environment) variables and local ones. Both are written in uppercase. The environment variables are global ones, which means they are available in all shells and don't vanish when you close one—unlike local Bash variables, which are only available in the current shell. 

Environment variables can contain data that can be used by multiple applications and are often used as a handy way to share configuration settings. In contrast to that, local Bash variables are just that, local. In our context of using Rake, you have the ability to access both via Ruby and in effect pass variables from the command line.

FYI

Just as a little aside, if you type env or ENV in your shell, you’ll get access to a whole bunch of environment variables. I redacted the list, but for a better understanding of what environment variables are and what they include, I encourage you to run it for yourselves.

Shell

1
env

Output

1
TERM_PROGRAM=Apple_Terminal
2
TERM=screen-256color
3
SHELL=/bin/bash
4
TMUX=/private/var/folders/4z/3np9k5ks62b1xpbn_w_lmrgh0000gr/T/tmux-504/default,4146,0
5
EDITOR=vim
6
LANG=en_US.UTF-8
7
TMUX_PANE=%1
8
is_vim=echo "#{pane_current_command}" | grep -iqE "(^|\/)g?(view|n?vim?x?)(diff)?$"
9
...
10
...
11
...

If you want to see a list of local Bash variables, you can run set.

Shell

1
( set -o posix ; set ) | less

The set command gives you a lot more output, but the above shows you the relevant bits right away.

Ruby’s ENV Class Method

Ruby offers a way to use environment and local Bash variables alike via a hash-like accessor. For our needs, when we pass a variable to a Rake task, it’s going to be a local Bash variable, which you can find in the list of variables running set or a variation of it. Ruby can read it out using ENV['VARIABLE'].

Shell

1
rake prepare_book BOOKTITLE='Confessions of a unicorn'

What I want to make clear, though, is that this variable won’t get added to the ENV list that your system uses—the stuff that you saw calling env from the shell. To add it to that list, you would need to export it. This is another story, but I thought I should make this clear.

Some Rakefile

1
task :prepare_book do
2
  book_title = ENV['BOOKTITLE'] || 'Working Title'
3
  puts "Do something with the #{book_title}"
4
end

In this task definition, you can see how we prepared to accept or incorporate the variable passed to the task invocation. Ruby’s ENV[BASHVARIABLE] does all the heavy lifting. If BOOKTITLE had been a global environment variable, though, we could have accessed it inside this task definition as well with this syntax.

Rake Parameter Syntax

The second approach is using pure Rake syntax. You simply pass variables into square braces. That approach is better, and you can keep things more isolated. Why involve Bash if Rake is perfectly capable of handling this? Plus you don’t have any Bash variables floating around that way. If you want to pass multiple arguments into a task, it’s a lot more elegant as well.

Shell

1
rake "create_mi6_agent[James, Bond, 007]"

Some Rakefile

1
task :create_mi6_agent, [:first_name, :last_name, :number] do |t, args|
2
  puts "Number #{args.number} is commander #{args.first_name} #{args.last_name}."
3
end

When you pass in more arguments than you have defined in your task, you can simply access them via args. args.extras displays an array of all the additionally passed in parameters. args.to_a shows you all the parameters—in an array as well, of course.

Tasks of Interest

Below is a short list of Rake tasks that come with Rails:

  • db
  • doc
  • tmp
  • stats
  • notes
  • about
  • secret
  • assets
  • routes

db

Below are a couple of useful tasks under the db namespace for running Active Record migrations:

rake db:version prints the current version of the schema. The output looks something like this:

1
Current version: 20160129135912

rake  db:migrate runs the last migration(s)—those which haven’t run yet. You can also pass it a specific migration to run.

Shell

1
rake db:migrate VERSION=20080906120000

rake db:create creates your database. If defaults to the development and test databases.

1
db/development.sqlite3
2
db/test.sqlite3

rake db:test:prepare makes sure that migrations that are already run on your development database are also run for your test database. If the test database’s schema were out of sync with your development database, it would not be very useful, of course.

rake db:drop:all drops both test and development databases by default.

rake db:migrate:up, rake db:migrate:down runs the up and down methods for the migration in question.

rake db:redo ensures that, after you have run a migration, the migration is reversible. It runs rake db:down first and then rake db:up.

rake db:rollback undoes the last migration.

rake db:drop drops by the development and test databases by default.

rake db:reset drops the databases first and sets them up again by loading the schema and seeding the database.

doc

rake doc:app generates documentation under doc/app. It creates HTML pages about your source code for easy browsing. Pretty cool!

Screenshot

A screenshot of the mission controllerA screenshot of the mission controllerA screenshot of the mission controller

rake doc:rails generates an API documentation under doc/api—also as HTML pages. Handy if you are offline, I guess.

tmp

The tmp directory in the root directory of your Rails app is the place for temporary files—most prominently files for sessions and cache. rake tmp:create sets you up with everything you need for dealing with temporary files. rake tmp:cache:clear clears the tmp/cache directory. rake tmp:sessions:clear clears the tmp/sessions directory.

stats

rake stats gives you a nice overview of your app.

1
+----------------------+-------+-------+---------+---------+-----+-------+
2
| Name                 | Lines |   LOC | Classes | Methods | M/C | LOC/M |
3
+----------------------+-------+-------+---------+---------+-----+-------+
4
| Controllers          |    89 |    69 |       6 |      18 |   3 |     1 |
5
| Helpers              |    13 |    13 |       0 |       1 |   0 |    11 |
6
| Models               |    89 |    54 |       6 |       7 |   1 |     5 |
7
| Mailers              |     0 |     0 |       0 |       0 |   0 |     0 |
8
| Javascripts          |    25 |     0 |       0 |       0 |   0 |     0 |
9
| Libraries            |     0 |     0 |       0 |       0 |   0 |     0 |
10
| Controller specs     |    99 |    81 |       0 |       0 |   0 |     0 |
11
| Feature specs        |    14 |    11 |       0 |       0 |   0 |     0 |
12
| Helper specs         |    45 |    12 |       0 |       0 |   0 |     0 |
13
| Model specs          |    10 |     8 |       0 |       0 |   0 |     0 |
14
| View specs           |    60 |    48 |       0 |       0 |   0 |     0 |
15
+----------------------+-------+-------+---------+---------+-----+-------+
16
| Total                |   444 |   296 |      12 |      26 |   2 |     9 |
17
+----------------------+-------+-------+---------+---------+-----+-------+
18
  Code LOC: 136     Test LOC: 160     Code to Test Ratio: 1:1.2

notes

You can leave notes in your code. You can prefix them in your comments with TODO, FIXME, OPTIMIZE.

Some Ruby file

1
# FIXME Something to fix here

2
class Agent < ActiveRecord::Base
3
  belongs_to :operation
4
  belongs_to :mission
5
6
...

When you run rake notes, Rake parses these prefixes and gets you a list of all these notes from your code. 

Shell

1
app/models/agent.rb:
2
  * [1] [FIXME] Something to fix here

You even get a detailed list where you find them—directory, filename, line number [Line Number], everything is included. Awesome, right?

about

rake about gives you an overview of version numbers for:

  • Rails
  • Ruby
  • RubyGems
  • Database adapter
  • Schema version
  • Middleware
  • Application root

and lots of other useful information.

secret

If you are paranoid about your session key and want to replace it, rake secret will generate a new pseudo-random key for you. It doesn't replace the key for you, though. The output in the shell looks like this:

1
b40a74b94cd93fed370fd4f8f9333633c03990b7d9128383511de5240acf3fa6b6b07127e875814fdadb32f1aa44d69c4e82592b0ce97f763ea216a21e61881d

assets

rake assets:precompile lets you precompile your assets under public/assets. If you want to get rid of older assets, just run rake assets:clean. Finally, running rake assets:clobber deletes the whole public/assets directory.

routes

rake routes might be the most important one. It shows you all the routes in your app.

Final Thoughts

Writing Rake tasks without knowing what’s going on under the hood gets boring pretty quickly. This article was a little warm-up and introduction for people who wanted to peek into Rake for the first time. 

I hope it covered all the basics without being too dry—after all, Rake is super dope and all, but at the same time, it’s maybe not the sexiest of toys. This basic knowledge of Rake, though, should give you all you need to get dangerous and expand your knowledge of the Rake tasks that are at your disposal.