Giter VIP home page Giter VIP logo

intro-to-rake's Introduction

Intro to Rake

Objectives

  1. Introduce Rake and Rake tasks.
  2. Understand what Rake is used for in our Ruby programs.
  3. Learn how to build a basic Rake task.

What is Rake?

Rake is a tool that is available to us in Ruby that allows us to automate certain jobs––anything from execute SQL to puts-ing out a friendly message to the terminal.

Rake allows us to define something called "Rake tasks" that execute these jobs. Once we define a task, that task can be executed from the command line.

Why Rake?

Every program has some jobs that must be executed now and then. For example, the task of creating a database table, the task of making or maintaining certain files. Before Rake was invented, we would have to write scripts that accomplish these tasks in BASH, or we would have to make potentially confusing and arbitrary decisions about what segment of our Ruby program would be responsible for executing these tasks.

Writing scripts in BASH is tough, and BASH just isn't as powerful as Ruby. On the other hand, for each developer to make his or her own decisions about where to define and execute certain common tasks related to databases or file maintenance is confusing.

Rake provides us a standard, conventional way to define and execute such tasks using Ruby.

Where did Rake Come From?

In fact, the C community was the first to implement the pattern of writing all their recurring system maintenance tasks in a separate file. They called this file the MakeFile because it was generally used to gather all of the source files and make it into one compiled executable file.

Rake was later developed by Jim Weirich as the task management tool for Ruby.

How to Define and Use Rake Tasks

Building a Rake task is easy, since Rake is already available to us as a part of Ruby. All we need to do is create a file in the top level of our directory called Rakefile. Here we define our task:

task :hello do
  # the code we want to be executed by this task
end

We define tasks with task + name of task as a symbol + a block that contains the code we want to execute.

If you open up the Rakefile in this directory, you'll see our :hello task:

task :hello do
  puts "hello from Rake!"
end

Now, in your terminal in the directory of this project, type:

rake hello

You should see the following outputted to your terminal:

hello from Rake!

Describing our Tasks for rake -T

Rake comes with a handy command, rake -T, that we can run in the terminal to view a list of available Rake tasks and their descriptions. In order for rake -T to work though, we need to give our Rake tasks descriptions. Let's give our hello task a description now:

desc 'outputs hello to the terminal'
task :hello do
  puts "hello from Rake!"
end

Now, if we run rake -T in the terminal, we should see the following:

rake hello       # outputs hello to the terminal

So handy!

Namespacing Rake Tasks

It is possible to namespace your Rake tasks. What does "namespace" mean? A namespace is really just a way to group or contain something, in this case our Rake tasks. So, we might namespace a series of greeting Rake tasks, like hello, above, under the greeting heading.

Let's take a look at namespacing now. Let's say we create another greeting-type Rake task, hola:

desc 'outputs hola to the terminal'
task :hola do
  puts "hola de Rake!"
end

Now, let's namespace both hello and hola under the greeting heading:

namespace :greeting do
desc 'outputs hello to the terminal'
  task :hello do
    puts "hello from Rake!"
  end

  desc 'outputs hola to the terminal'
  task :hola do
    puts "hola de Rake!"
  end
end

Now, to use either of our Rake tasks, we use the following syntax:

rake greeting:hello
hello from Rake!

rake greeting:hola
hola de Rake!

Common Rake Tasks

As we move towards developing Sinatra and Rails web applications, you'll begin to use some common Rake tasks that handle the certain database-related jobs.

rake db:migrate

One common pattern you'll soon become familiar with is the pattern of writing code that creates database tables and then "migrating" that code using a rake task.

Our Student class currently has a #create_table method, so let's use that method to build out our own migrate Rake task.

We'll namespace this task under the db heading. This namespace will contain a few common database-related tasks.

We'll call this task migrate, because it is a convention to say we are "migrating" our database by applying SQL statements that alter that database.

namespace :db do
  desc 'migrate changes to your database'
  task :migrate => :environment do
    Student.create_table
  end
end

But, if we run rake db:migrate now, we're going to hit an error.

Task Dependency

You might be wondering what is happening with this snippet:

task :migrate => :environment do
...

This creates a task dependency. Since our Student.create_table code would require access to the config/environment.rb file (which is where the student class and database are loaded), we need to give our task access to this file. In order to do that, we need to define yet another Rake task that we can tell to run before the migrate task is run.

Let's check out that environment task:

# in Rakefile

task :environment do
  require_relative './config/environment'
end

After adding our environment task, running rake db:migrate should create our students table.

rake db:seed

Another task you will become familiar with is the seed task. This task is responsible for "seeding" our database with some dummy data.

The conventional way to seed your database is to have a file in the db directory, db/seeds.rb, that contains some code to create instances of your class.

If you open up db/seeds.rb you'll see the following code to create a few students:

require_relative "../lib/student.rb"

Student.create(name: "Melissa", grade: "10th")
Student.create(name: "April", grade: "10th")
Student.create(name: "Luke", grade: "9th")
Student.create(name: "Devon", grade: "11th")
Student.create(name: "Sarah", grade: "10th")

Then, we define a rake task that executes the code in this file. This task will also be namespaced under db:

namespace :db do

  ...

  desc 'seed the database with some dummy data'
  task :seed do
    require_relative './db/seeds.rb'
  end
end

Now, if we run rake db:seed in our terminal (provided we have already run rake db:migrate to create the database table), we will insert five records into the database.

If only there was some way to interact with our class and database without having to run our entire program...

Well, we can build a Rake task that will load up a Pry console for us.

rake console

We'll define a task that starts up the Pry console. We'll make this task dependent on our environment task so that the Student class and the database connection load first.

desc 'drop into the Pry console'
task :console => :environment do
  Pry.start
end

Now, provided we ran rake db:migrate and rake db:seed, we can drop into our console with the following:

rake console

This should bring up the following in your terminal:

[1] pry(main)>

Let's check to see that we did in fact successfully migrate and seed our database:

[1] pry(main)> Student.all
=> [[1, "Melissa", "10th"],
 [2, "April", "10th"],
 [3, "Luke", "9th"],
 [4, "Devon", "11th"],
 [5, "Sarah", "10th"]]

We did it!

View Intro to Rake on Learn.co and start learning to code for free.

intro-to-rake's People

Contributors

annjohn avatar dakotalmartinez avatar dandanberry avatar devinburnette avatar franknowinski avatar gj avatar maxwellbenton avatar pletcher avatar sammarcus avatar sgharms avatar simque avatar sophiedebenedetto avatar victhevenot avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

intro-to-rake's Issues

needs tests!

Needs tests to make sure students completed this walk through

task :hello not defined outside of the namespace

Under the heading, "How to Define and Use Rake Tasks," the reader is advised that there a task :hello within the Rakefile, however, this task does not exist outside of the namespace, :greeting. Therefore, when the reader is then asked to type rake hello into the console, an error message is returned.

The rspec tests are missing a test for "rake console".

Hello. The README had us make a task for Rake called :console, but there isn't an rspec test for that. I don't know if that was intentional or not, but I wanted to let you guys know.

Thanks for checking this out, and Happy Holidays!

Sdcrouse

line 51 in Readme.md issue on osx 10.10 and ruby 2.2.3

I received an error when I tried the instructions on line 51 in Readme.md: rake greeting::hello. Instead I had to type rake hello to get the correct output in terminal.

(upon further reading it looks like this is because the hello task isn't yet namespaced at that point in the lesson)

System info:
~/.rvm/rubies/ruby-2.2.3/bin/rake
OSX 10.10.5

Suggestion for Right Column on Learn Lessons/Labs

This suggestion is not specific to this lab.

I would find it convenient if the right column could be collapsed or made hidden since I like to use the README in the browser side by side with my text editor. If I could hide the column with the Questions and Tests then I could utilize monitor space better and more easily than manually dragging windows. I was thinking of a toggle arrow, but anyway to hide the column would be helpful. Anyways, just an idea.

rake greeting:hello example does not work

Now, in your terminal in the directory of this project, type:
rake greeting:hello
You should see the following outputted to your terminal:
hello from Rake!


This example does not work because we have not given the namespace to our rakefile yet.

No :hello task

This lesson says "If you open up the Rakefile in this directory, you'll see our :hello task", but there is no hello task in the Rakefile.

Rake task output inaccurate

rake greeting:hola
hello from Rake!

rake greeting:hola
hola de Rake!

Should be

rake greeting:hello
hello from Rake!

rake greeting:hola
hola de Rake!

Inheriting without Rails version target raises error.

ERROR
DEPRECATION WARNING: Directly inheriting from ActiveRecord::Migration is deprecated. Please specify the Rails release the migration was written for:

SOLUTION
Placing the integer value of the version # of Rails in brackets at the end of statement satisfies requirement.

(ex.) class CreateArtists < ActiveRecord::Migration[4.2]

Rake Console

I believe the instructions in this lesson may need to be re-written. The code along runs very smoothly up until the point of implementing rake console. The directions call for the following:

"Now, provided we ran rake db:migrate and rake db:seed, we can drop into our console with the following:"

"rake console"

By using the terminal command 'rake console", as a student this leads me to believe that the code should be written as the following based that the instructed command does not ask to be written as "rake db:console" (notice the console task as outside of the scope of the namespace db :


namespace :db do
desc 'setup environment dependencies and load data'
task :environment do
require_relative './config/environment'
end
desc 'migrate changes to your database'
task :migrate => :environment do
Student.create_table

  end
  desc 'seed the database with some dummy data'
  task :seed do
    require_relative './db/seeds.rb'
  end

end

  desc 'drop into the Pry console'
  task :console => :environment do
    Pry.start
  end

However running this code did not work to have a loaded pry environment. I was able to have the code work however by having the console task nested with the :db namespace in the following code:

namespace :db do
desc 'setup environment dependencies and load data'
task :environment do
require_relative './config/environment'
end
desc 'migrate changes to your database'
task :migrate => :environment do
Student.create_table

  end
  desc 'seed the database with some dummy data'
  task :seed do
    require_relative './db/seeds.rb'
  end

  desc 'drop into the Pry console'
  task :console => :environment do
    Pry.start
  end

end


After implementing this code in this manner I was able to get the pry loaded and have test cases passing.

I believe the instructions should indicate this more clearly. If not then I understand that I misunderstood an instruction and I would appreciate insight as to why the lesson is correctly written.

Thank you!

confusing

task console => environment and task environment work outside of namespace db but not inside it.

There is no clear cut direction on where to place it, and the with the last instruction being db:seed it is automatically assumed it should be in namespace :db.

please fix the readme

source -Chris Henry tech coach 9/13

namespacing vs instructions confusion

All line numbers refer to the readme.md file:

Instructions for "rake console" beginning on line 201 don't specify whether to put the console code inside the :db namespace or outside. If it should be placed inside, then the instructions on line 215 regarding how to run the console should read: rake db:console

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.