Thor - Awesome CLI apps

Ever wanted to create an awesome command line application but was lost in the sea of options parsing? Well, if you did, and even if you didn’t, Thor is here to help you.


But what is Thor exactly? It is a powerful toolkit for writing command line applications in ruby that is used in various well known projects such are Rails, Vagrant, Bundler, and similar. It can be even used as a replacement for rake for creating task like methods and functions.

Baby steps with Thor #

When I stumble across something cool, my first instinct is to share and point out the most awesome parts of that thing. Usually, this is the worst approach for presenting things to other people. So now, I will try to hold back my geek instincts and start out simple. With a hello awesome world application. Here it is.

require "thor"

class  AwesomeHelloWorld < Thor

  desc "hello PLANET", "say hello to PLANET"
  def hello(planet)
    puts "Hello #{planet}"



Save it to an appropriately named file ahw.rb and try to run it.

$ ruby ahw.rb

  ahw hello PLANET   # say hello to PLANET
  ahw help [TASK]     # Describe available tasks or one specific task
$ ruby ahw.rb hello uranus
hello uranus

As you can see in the above script has done so much instead of us. It created a help screen, it has a description for all of our tasks, and it can even parse and execute them appropriately.

Digging deeper #

Let’s explore more of this awesomeness. Every task in a Thor application can accept command line flags with single or double dashes. To demonstrate this capability I will add a --reverse flag to our little hello task.

desc "hello PLANET", "say hello to PLANET"
options :reverse => :boolean
def hello(planet)
  puts "Hello #{options{:reverse] ? planet.reverse : planet}"

Now if we call our task with the reverse flag it should display the name of the planet in reverse.

$ ruby hello MARS --reverse
hello SRAM

Summary #

Thor is awesome.

You should use Thor when you want to create cli apps.

You shall thus also be awesome.

Happy hacking!


Now read this

Pipes in the shell

Here is a story of my typical work session in the shell. It starts by a wish to make the computer execute some of my commands. For example, I want to list all the files in the current directory. From prior knowledge I know that the ls... Continue →