aneta_bielska [:blog]

Ruby rake tasks
#ruby #rake

The problem

I want to run scripts on server. For example to populate a database.

The solution

Use rake gem.

What is rake?

More offical explanation:

Rake is a build language, similar in purpose to make and ant. Like make and ant it’s a Domain Specific Language, unlike those two it’s an internal DSL programmed in the Ruby language. In this article I introduce rake and describe some interesting things that came out of my use of rake to build this web site: dependency models, synthesized tasks, custom build routines and debugging the build script.

Simplified answer:

Rake is a tool you can use with Ruby projects. It allows you to use ruby code to define “tasks” that can be run in the command line. Rake can be downloaded and included in ruby projects as a ruby gem. Once installed, you define tasks in a file named “Rakefile” that you add to your project. We call it a “build tool” because Rake comes with some libraries that make it easy to do tasks that are common during the build/deploy process, like file operations (creating, deleting, renaming, & moving files), publishing sites via FTP/SSH, and running tests. For more information, here’s the project documentation:


Firstly add rake to Gemfile and run bundle. Another step is to add a Rakefile. This is a file where we keep scripts definitions. I also added tasks directory where I will keep my scripts.

Rakefile content:

task default: [:hello_world]

desc 'say hello'
task :hello_world do
  ruby "tasks/hello_world.rb"

Let’s also add some content to hello_world.rb:

# tasks/hello_world.rb

puts "Hello, world!"

Now we can open a terminal and run:

$ rake hello_world

the output should print to the console defined in hello_world.rb content.

$ rake hello_world
Hello, world!

Since we defined :hello_world as a default task running $ rake will work the same as $ rake hello_world.

To check available tasks run:

$ rake -T

It will print tasks list with full commands and commented out description texts.

rake hello_world  # say hello

This is enough to start creating your own powerful rake tasks. Rake tasks have tendency to pile up, here is a list of good practices to keep it clean. A rake task is good when:

You may also enjoy:

#servers (1) #hosting (1) #sinatra (2) #assets (1) #sprockets (1) #react-js (1) #data-mapper (1) #ROM (1) #sequel (1) #ORM (1) #pg (1) #sqlite3 (1) #postgresql (1) #ruby (4) #ubuntu (1) #heroku (1) #git (1) #css (3) #cors (1) #same-origin-policy (1) #rake (1) #web-scraping (1) #ruby-on-rails (1) #brug (1) #elixir (1) #benchmark (1)