Include this module to gain access to the “canonical command-line app structure” DSL. This is a very lightweight layer on top of what you might normally write that gives you just a bit of help to keep your code structured in a sensible way. You can use as much or as little as you want, though you must at least use main to get any benefits.

Further, you must provide access to a logger via a method named logger. If you include Methadone::CLILogging, this will be done for you

You also get a more expedient interface to OptionParser as well as checking for required arguments to your app. For example, if we want our app to accept a negatable switch named “switch”, a flag named “flag”, and two arguments “needed” (which is required) and “maybe” which is optional, we can do the following:

#!/usr/bin/env ruby

require 'methadone'

class App
  include Methadone::Main
  include Methadone::CLILogging

  main do |needed, maybe|
    options[:switch] => true or false, based on command line
    options[:flag] => value of flag passed on command line

  # Proxy to an OptionParser instance's on method
  on("--flag VALUE")

  arg :needed
  arg :maybe, :optional

  defaults_from_env_var SOME_VAR
  defaults_from_config_file '.my_app.rc'


Our app then acts as follows:

$ our_app 
# => parse error: 'needed' is required
$ our_app foo
# => succeeds; "maybe" in main is nil
$ our_app --flag foo
# => options[:flag] has the value "foo"
$ SOME_VAR='--flag foo' our_app
# => options[:flag] has the value "foo"
$ SOME_VAR='--flag foo' our_app --flag bar
# => options[:flag] has the value "bar"

Note that we've done all of this inside a class that we called App. This isn't strictly necessary, and you can just include Methadone::Main and Methadone::CLILogging at the root of your bin file if you like. This is somewhat unsafe, because self inside the bin file is Object, and any methods you create (or cause to be created via include) will be present on every object. This can cause odd problems, so it's recommended that you not do this.

Included Modules
Class Public methods
# File lib/methadone/main.rb, line 77
def self.included(k)
Instance Public methods

Sets the name of an arguments your app accepts. Note that no sanity checking is done on the configuration of your arguments you create via multiple calls to this method. Namely, the last argument should be the only one that is a :many or a :any, but the system here won't sanity check that.


name of the argument to appear in documentation This will be converted into a String and used to create the banner (unless you have overridden the banner)


list (not Hash) of options:


this arg is required (this is the default)


this arg is optional


only one of this arg should be supplied (default)


many of this arg may be supplied, but at least one is required


any number, include zero, may be supplied

A string

if present, this will be documentation for the argument and appear in the help

# File lib/methadone/main.rb, line 245
def arg(arg_name,*options)

Set the path to the file where defaults can be configured.

The format of this file can be either a simple string of options, like what goes in the environment variable (see defaults_from_env_var), or YAML, in which case it should be a hash where keys are the option names, and values their defaults.

Relative paths will be expanded relative to the user's home directory.


path to the file. If relative, will look in user's HOME directory. If absolute, this is the absolute path to where the file should be.

# File lib/methadone/main.rb, line 146
def defaults_from_config_file(filename,options={})
  @rc_file = File.expand_path(filename, ENV['HOME'])

Set the name of the environment variable where users can place default options for your app. Omit this to disable the feature.

# File lib/methadone/main.rb, line 132
def defaults_from_env_var(env_var)
  @env_var = env_var

Set the description of your app for inclusion in the help output.


a short, one-line description of your app

# File lib/methadone/main.rb, line 251
def description(desc)

Start your command-line app, exiting appropriately when complete.

This will exit your program when it completes. If your main block evaluates to an integer, that value will be sent to Kernel#exit, otherwise, this will exit with 0

If the command-line options couldn't be parsed, this will exit with 64 and whatever message OptionParser provided.

If a required argument (see arg) is not found, this exits with 64 and a message about that missing argument.

# File lib/methadone/main.rb, line 162
def go!
  result = call_main
  if result.kind_of? Fixnum
    exit result
    exit 0
rescue OptionParser::ParseError => ex
  logger.error ex.message
  exit 64 # Linux standard for bad command line

Configure the auto-handling of StandardError exceptions caught from calling go!.


if true, go! will not catch StandardError exceptions, but instead allow them to bubble up. If false, they will be caught and handled as normal. This does not affect Methadone::Error exceptions; those will NOT leak through.

# File lib/methadone/main.rb, line 126
def leak_exceptions(leak)
  @leak_exceptions = leak

Declare the main method for your app. This allows you to specify the general logic of your app at the top of your bin file, but can rely on any methods or other code that you define later.

For example, suppose you want to process a set of files, but wish to determine that list from another method to keep your code clean.

#!/usr/bin/env ruby -w

require 'methadone'

include Methadone::Main

main do
  files_to_process.each do |file|
    # process file

def files_to_process
  # return list of files


The block can accept any parameters, and unparsed arguments from the command line will be passed.

Note: go! will modify ARGV so any unparsed arguments that you do not declare as arguments to main will essentially be unavailable. I consider this a bug, and it should be changed/fixed in a future version.

To run this method, call go!

# File lib/methadone/main.rb, line 116
def main(&block)
  @main_block = block

Calls the on method of opts with the given arguments (see RDoc for opts for the additional help provided).

# File lib/methadone/main.rb, line 225
def on(*args,&block)

Returns a Hash that you can use to store or retrieve options parsed from the command line. When you put values in here, if you do so before you've declared your command-line interface via on, the value will be used in the docstring to indicate it is the default. You can use either a String or a Symbol and, after go! is called and the command-line is parsed, the values will be available as both a String and a Symbol.


main do
  puts options[:foo] # put the value of --foo that the user provided

options[:foo] = "bar" # set "bar" as the default value for --foo, which
                      # will cause us to include "(default: bar)" in the
                      # docstring

on("--foo FOO","Sets the foo")
# File lib/methadone/main.rb, line 276
def options
  @options ||= {}

Returns an OptionParser that you can use to declare your command-line interface. Generally, you won't use this and will use on directly, but this allows you to have complete control of option parsing.

The object returned has an additional feature that implements typical use of OptionParser.

opts.on("--flag VALUE")

Does this under the covers:

opts.on("--flag VALUE") do |value|
  options[:flag] = value

Since, most of the time, this is all you want to do, this makes it more expedient to do so. The key that is is set in options will be a symbol and string of the option name, without the leading dashes. Note that if you use multiple option names, a key will be generated for each. Further, if you use the negatable form, only the positive key will be set, e.g. for --[no-]verbose, only :verbose will be set (to true or false).

As an example, this declaration:

opts.on("-f VALUE", "--flag")

And this command-line invocation:

$ my_app -f foo

Will result in all of these forms returning the String “foo”:

  • options['f']

  • options[:f]

  • options['flag']

  • options[:flag]

Further, any one of those keys can be used to determine the default value for the option.

# File lib/methadone/main.rb, line 219
def opts
  @option_parser ||=,options)

Set the version of your app so it appears in the banner. This also adds –version as an option to your app which, when used, will act just like –help (see version_options to control this)


the current version of your app. Should almost always be YourApp::VERSION, where the module YourApp should've been generated by the bootstrap script


controls how the version option behaves. If this is a string, then the string will be used as documentation for the –version flag. If a Hash, more configuration is available:


the string to document the –version flag if you don't like the default


if true, –version will just show the app name and version - no help


if provided, this can give limited control over the format of the compact version string. It should be a printf-style string and will be given two options: the first is the CLI app name, and the second is the version string

# File lib/methadone/main.rb, line 295
def version(version,version_options={})
  if version_options.kind_of?(String)
    version_options = { :custom_docs => version_options }
  version_options[:custom_docs] ||= "Show help/version info"
  version_options[:format] ||= "%s version %s"
  opts.on("--version",version_options[:custom_docs]) do 
    if version_options[:compact]
      puts version_options[:format] % [::File.basename($0),version]
      puts opts.to_s
    exit 0