Learning Management Platform for Written Tutorial Series.

Ruby on Rails Rake

Ruby on Rails Rake

Introduction

Rake is a command line utility program that rails uses to automate commonly performed tasks. It is written in ruby. We already saw rake in action in the previous tutorial where we used it to automatically create the database for us.

This tutorial introduces you to basic rake commands that you need to know and how to create your own custom rake commands.

Topics to be covered

We will cover the following topics in this tutorial

  • Tutorial pre-requisites
  • Why you should understand rake basics?
  • Rake Commands Syntax
  • Common Rake Tasks
  • Rake Environment
  • Rake Custom Task
  • Run Rake task from within another rake task

Tutorial pre-requisites

This tutorial assumes you have;

  • HTML basics – this is an added advantage. You can still write rails code without knowing HTML but it’s highly recommended.
  • Installed ruby on rails version 4 and above
  • WEBrick webserver or any other webserver that supports ruby on rails
  • MySQL already installed, up and running
  • You have an IDE i.e. Aptana Studio or text editor such as sublime text.
  • Command line prompt or terminal

Why you should understand rake basics?

One of the things that speed up developing ruby on rails applications is because you can automate most of the tasks. Rake plays an important role in accomplishing this. Most of the tasks such as running unit tests, migrations, seeding etc. will be done via rake commands. Knowing the basics of rake while transform you into a productive rails developer.

Rake Command Syntax

All rake commands have the following basic syntax

rake command_name [options]

HERE,

  • rake tells the command prompt / terminal to use the rake program
  • command_name [options] is the name of the task that you want rake to perform for you.

Rake uses prefixes to group similar commands together i.e. db for all commands for the database start with db, assets for all tasks for assets. If there is a sub group within a group then the same logic is applied i.e. db:schema is the prefix for all rake database tasks that deal with the database schema.

Rake Common Tasks

In the previous tutorial Ruby on Rails Database, we created a project movies_library. We will continue working with the same tutorial project.

I am assuming you are using windows and have movies_libarry project on drive C:\ in Sites directory. The knowledge still applies to other platforms with minimal tweeks.

Open the command prompt

Run the following command to browser to the project root

cd "C:\Sites\movies_library"

Rake get Ruby on Rails project information

We will start by viewing information pertaining to our project

Run the following command

rake about

You will get results similar to the following

Rake about task

As you can see from the above image, you will get information about the versions of the various programs that you are using including the version of rake itself. It will also show you the application root, environment and database adapter.

Rake Display all Tasks

Let’s start with tasks that have the description set.

Run the following command

rake -T

You will get results similar to the ones shown below

Rake list tasks

The above command will give you all of the available rake tasks that have descriptions of what each task does set.

You can pass a second parameter to the above command to filter the results that are returned. Let’s say you are only interested in rake commands that deal the database. You can run the following command

rake –T db

The above command will return only rake tasks that have the prefix db

What if you want to display all available tasks regardless of whether the description has been set or not? You can use the following command to do that.

rake –P

You will get a more detailed list of available rake commands including those that do not have the description set.

Rake: display task path

This command is useful when you want to know the path where rake is loading the task from. The general syntax is as follows

rake –W task:name

Let’s say we are interested in knowing the path of the rake task db:migrate

Run the following command

rake –W db:migrate

You will get results similar to the ones shown below

Rake task path

Rake most commonly used tasks

The following table shows some of the most commonly used tasks. The list not exhaustive, we will cover more rake tasks as we proceed in the tutorial series.

S/N TASK DESCRIPTION EXAMPLE
1 db:migrate Run migration files rake db:migrate
2 db:rollback Rollback a migration. Optionally you can specific the version number rake db:rollback
3 db:seed Run database seeds rake db:seed
4 db:create Creates the database via rake rake db:create
5 db:drop Drops the database rake db:drop
6 test Used to run unit tests rake test
7 routes Display all the defined routes rake routes
8 tmp:clear Clears sessions, cache etc. data rake tmp:clear
9 stats Generates statistical information about the code rake stats

Rake Environment

By default, rake tasks runs using the development environment settings i.e. database connections

If you would like to use a different environment, you can set the environment to a different one when running tasks and rake will use the specified environment settings.

The following command shows how to dump the db schema to the production environment

rake db:schema:dump RAILS_ENV=production

Rake Custom Task

Ruby on Rails comes with a lot of tasks out of the box but they will be times when you will want to create your own custom tasks. The good news is rails allows you to create your own tasks.

Rake Custom Task Directory

The custom rake tasks should be stored in the directory /lib/tasks in the root of the project. The rake file should end with the .rake file extension.

Simple Rake Custom Task

Let’s create a simple hello world rake task

Create a new file raven.rake in /lib/tasks directory. You can use any name for the file

Update the code in /lib/tasks/raven.rake

task :hello do
    puts "Hello World!"
end

HERE,

  • task :hello defines a new task hello
  • puts "Hello World!" prints the words Hello World! in the console

Open the command prompt / terminal and browser to the project root

Run the following rake custom task

rake hello

You will get the following results

Hello World!

Rake Custom Task Pass Command Line Parameters

Let’s create a new task in the same file that accepts a command line argument and display it in the console.

Add the following task definition

task :greet, [:name] do |t, args|
    puts "Hello #{args[:name]}"
end

HERE,

  • task :greet, [:name] do |t, args| defines a task greet that accepts a parameter name
  • puts "Hello #{args[:name]}" prints the value of the variable name in the args array

Let’s now test our custom rake task

Run the following rake command

rake greet[Rodrick]

You will get the following output

Hello Rodrick

Accessing rails environment from within custom rake task

We have been working with basic examples of custom rake tasks and creating the boilerplate code ourselves. In this section, we will look at how we can auto generate custom tasks, introduce the concept of name spaces and access the rails environment from our custom task.

To make our example more interesting, let’s create a migration file and seed some records. We will need some data from the database for this task. I am assuming you have been following the tutorials series and created the movies_library database already.

Run the following command to generate the database table model and migration file

rails g model genre –m

The above command will create a database model and migration file

Open /db/migration/20151118071436_create_genres.rb Note: your timestamp will be different

Modify the code to the following

class CreateGenres < ActiveRecord::Migration
    def self.up
        create_table :genres do |t|
            t.column :name, :string
        end

        Genre.create :name => "Horror"
        Genre.create :name => "Action"
        Genre.create :name => "Romance"
        Genre.create :name => "Mystery"
        Genre.create :name => "History"
    end

    def self.down
        drop_table :genres
    end
end

HERE,

  • The above code creates a table genres and uses the model Genre to create dummy records. We will talk more about migrations in the next tutorial. If you check the database movies_library_development, you should be able to see the table genres and database records that we created.

Namespaces allow us to avoid task name collisions. What we have been doing so far did not consider using namespaces. We will use namespaces in this section

We will now create new custom rake tasks using rails generator.

Run the following rails command

rails g task movies about rand_genre

HERE,

  • The above command generates boiler plate code for our task. movies is the namespace and file name, about and rand_genre are tasks within the movies namespace

Open /lib/tasks/movies.rake

You will get the following code

namespace :movies do
  desc "TODO"
  task about: :environment do
  end

  desc "TODO"
  task rand_genre: :environment do
  end

end

HERE,

  • namespace :movies do defines a namespace movies. All tasks defined within this task file will be called via movies:task_name
  • desc "Displays information about movies custom rake tasks" sets the description for the task. The description is displayed when you run the rake command rake –T
  • task about: :environment do defines the task about and makes the rails environment available to the task

Modify the code to the following

namespace :movies do
  desc "Displays information about movies custom rake tasks"
  task about: :environment do
    puts "Movies custom rake custom tasks"
  end

  desc "Pick and display a random genre from the database"
  task rand_genre: :environment do
    genre = Genre.offset(rand(Genre.count)).first

    puts "The genre chosen by science is: #{genre.name}"
  end
end

HERE,

  • genre = Genre.offset(rand(Genre.count)).first retrieves a random record from the database and assigns the result to the variable genre. This code uses the model Genre
  • puts "The genre chosen by science is: #{genre.name}" displays the name of the genre in the console window

Let’s now test our custom tasks

Run the following command

rake –T movies

You will get the following results

Rake custom task

Let’s now pick a random movie genre from the database

rake movies:rand_genre

You will get any of the genres from the database

Run Rake task from within another rake task

Let’s say you want to use an existing rake task in your custom task. For the sake of demonstrate, we will invoke the rake task about.

Modify the code for about task to the following

desc "Invokes built in task about"
task about: :environment do
    Rake::Task["about"].invoke
end

HERE,

  • Rake::Task["about"].invoke invokes the built in task about

Summary

In this tutorial, we have learnt the basics of rake, some of the most commonly used commands and how to create our own custom commands. Custom commands come in handy when you want to automate common tasks that do not ship with rake by default.

What’s next?

In the next tutorial, we will continue with our tutorial project and look at database migrations and seeding.

If you found this tutorial useful, support us by using the social media buttons to like and share the tutorial. If you didn’t find it useful, please use the comments section below to let us know how we can do better next time.

Each week, a new Ruby on Rails tutorial is added to our collection. Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when the collection is updated.

Tutorial History

Tutorial version 1: Date Published 2015-11-18


...