1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Command Line Tools using Execute


There are numerous libraries to parse command line parameters, but they all involve some sort of API or meta language to define these arguments. The Execute gem skips this step and provides a command line interface for a class with just a few lines of code added. The only catch is that you code must follow a few simple conventions.

Getting started with Execute is extremely simple. It's a simple gem install, and to see how to use it, it's best to just look at an example program first.

$ gem install execute

And the example code.

#!/usr/bin/env ruby
require 'net/http'
require 'uri'
require 'executable'

class LinkChecker
  include Executable

  def allow_redirects=(redir)
    @allow_redirects = redir

  def check(url)
    puts "Checking #{url}"
    uri = URI.parse(url)

    response = nil
    Net::HTTP.start(uri.host, uri.port) do|http|
      response = http.head(uri.path)

    if response.code == "200"
      puts "OK"
    elsif response.code =~ /^3../ && @allow_redirects
      puts "REDIRECTED (#{response.code})"
      puts "BROKEN (#{response.code})"


The first thing you'll notice is the initial state of the object is set with a few assignment methods (those ending with an equal sign). These are the methods that get mapped to command line switches. You'll also notice that there are two types.

The first type are true/false switches. These aren't intended to be passed anything, they're just true if present and false if not. In this example, allow_redirects= sets the @allow_redirects with its argument. This is intended to be accessed from the command line using the switch --allow_redirects. This will cause allow_redirects=(true) to be called.

The second type is to set a value. This type is almost identical , however it's intended to be used with a value passed on the command line. For example, --url=http://ruby.about.com/. This will cause url=('http://ruby.about.com/') to be called.

Finally, any other words on the command line are called as a method call and arguments. In this example, the check method is the only command and it takes a single argument. So, put all together, it looks something like this to call this class from the command line.

$ ./check.rb --allow_redirects check http://ruby.about.com/
Checking http://ruby.about.com/

And, of course, this class can be used from Ruby as well. This is the same code, the same interface, from both the command line and from Ruby. You can find out more about Executable on its homepage.

  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Command Line Tools using Execute

©2014 About.com. All rights reserved.