### 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.

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: http://rake.rubyforge.org/.

### Example

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'
end


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.

\$ 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:

• It has a meaningful and simple description.
• It uses namespace to group similar or related tasks.
• Its file structure follows the namespaces structure.
• It’s isolated on a class so we can re use it and test it with ease.
• It displays details about it progress without being too verbose.
• Its has it own log file containing start datetime, end datetime, how much did the task last and all the errors.