DEV Community

Shreeprabha bhat
Shreeprabha bhat

Posted on

RAKE IN RUBY

I had been working on ruby on rails from past few days and I had come across few commands like rake -T, rake db:migrate etc, but had never wondered what rake actually is. This made me to dig this topic and am sharing the little much knowledge I gained here today.

WHAT IS RAKE?
It is a tool in ruby that allows to run tasks, migrate database, test executions and some other repetitive tasks. Rake stands for "Ruby Make" and it is specially designed for ruby projects.

HOW DOES RAKE WORK?
Lets consider a example where a person tries to message and call another person.

task :message do
    puts "Hey!! What's up!"
end

task :call do
    puts "Hey! Its been long since we met so thought of calling you!"
end
Enter fullscreen mode Exit fullscreen mode

We can run the above tasks using the below rake command

$rake message
#Output: Hey!! What's up!
$rake call
#Output: Hey! Its been long since we met so thought of calling you!
Enter fullscreen mode Exit fullscreen mode

Rake tasks can also be dependent on other rake tasks they can also have parameters passed to them. Wondering how? Below is an example.

Consider an example where a student has exam. Writing an exam involves several sub tasks in them maybe from preparing a time table to waiting for the results it's a series of steps. So how can we sum up these sub tasks using rake tasks. Lets explore.

task :timetable do
     puts "Prepare timetable"
end

task :study=>timetable do
     puts "Study according to timetable"
end

task :exam=>study do
     puts "Write what you studied"
end

task :result=>[:timetable, :study, :exam]

Enter fullscreen mode Exit fullscreen mode

In this example running 'rake result' will run 'timetable' first later 'study' and then 'exam'.

We can also create custom rake tasks using namespace.

namespace :exam do
    desc "Give exam"
    task :write do
         puts "Write exam"
    end
end
Enter fullscreen mode Exit fullscreen mode

We can run the above rake task using 'rake exam:write'.

RAILS SPECIFIC RAKE TASKS
Below are some commonly used rails specific rake commands.
rake -T Used do list rake tasks
rake db:migrate Apply database migrations
rake test Run the test suite
rake db:seed Populate database with initial data.
rake -t Debugging mode

CONCLUSION
Rake integrates seamlessly with rails and makes it a powerful tool that can handle the development perfectly. From running test cases to migrating database rake supports a smooth workflow.

Top comments (1)

Collapse
 
vidyarathna profile image
Vidyarathna Bhat

Great explanation! This really clarifies what Rake is and how it can be used in Ruby on Rails projects. I especially liked the examples you provided—they made the concepts easy to understand. Looking forward to more posts like this! 😃