Acme Sprockets

Example Ruby CLI Program as Gem

I'm a software tool guy—I frequently craft and use a variety of simple (and some not so simple) tools to make my projects and computer life easier. While I use a variety languages, I've been using Ruby more and more over the last couple of years. I like to share with my colleagues, so I figured I'd create gems out some of these tools. This is really easy to do.

Rather than start with on my real tools, I created a super-simple CLI (command-line interface) program as an example to understand the method. Of course a "hello world" program is traditional. As I work on this, I'm somewhere over the Atlantic flying home from a client in Sweden. Ergo, I decided to call my example program and gem "hej" after the Swedish greeting.

The directory structure and files are as follows:

hej/
  Rakefile
  bin/
    hej
  lib/
    hej.rb

The very simple command-line program is bin/hej which consists of the following Ruby code:

#!/usr/bin/env ruby

begin
  require 'hej'
rescue LoadError
  require 'rubygems'
  require 'hej'
end

Hej.application.run

It will call the actual application in lib/hej.rb:

#
# This is the main file for the Hej application.  It expects to be called:
#
#   Hej.application.run
#

module Hej

  class << self

    def application
      @application ||= Hej::Application.new
    end
        
  end

  class Application

    def run
      puts "Hej!"
    end
 
  end

end

Finally, the Rakefile which will package the gem:

# -*- ruby -*-

require 'rubygems'
require 'rake/gempackagetask'

PKG_FILES = FileList[
  'lib/**/*.rb',
  'bin/*'
]

spec = Gem::Specification.new do |s|

  s.name    = "hej"
  s.version = "1.0.0"
  s.summary = "The sample Hej gem"

  s.author   = "Trey Kinkead"
  s.homepage = "http://www.acmesprockets.com/"

  s.files = PKG_FILES.to_a

  s.require_path = "lib"
  s.bindir = "bin"
  s.executables = ["hej"]
  s.default_executable = "hej"

end


#
# The below will automagically create tasks
#
# :package
# :clobber_package
# :repackage
# ...
#
# (see rake/lib/packagetask.rb for details)
# 
Rake::GemPackageTask.new(spec) do |pkg|
  pkg.gem_spec = spec
end

# make :package the default
task :default => [:package]

# vim: syntax=Ruby

The GemPackageTask automatically creates a number of methods including "pkg" which I made default. Thus, to create the package, I only need to invoke rake. The gem will be created as pkg/hej-1.0.0.gem. This can of course be distributed and installed with gem (e.g., gem install pkg/hej-1.0.0.gem).

Of course a real gem/application should probably include more such as tests, rdoc, a README, license, etc. but this is purposely a simple example.

Hope this helps.

Navigation