Project

Profile

Help

Writing executables in Ruby

Introduction

This pages gives a guideline for writing executable scripts in Ruby.

Current directory

  • all executable scripts must not require directory change and should work from a repository root

Command line arguments and actions

  • all command line arguments must be non-positional
  • no manual parsing of arguments, use special libs instead (getoptlong for example)

Logic division

  • all script logic is wrapped into separated functions/ classes
  • logic is called inside main function

Guarding executable code from being run when script is included

Script must contain following code at the bottom

if File.identical?(__FILE__, $0)
  main
end

Template

#!/usr/bin/env ruby

require 'getoptlong'

# Command line options
SOME_OPTION = '--some'
HELP_OPTION = '--help'

def help
   puts 'Help content'
   exit 0
end

def parse_options
  opts = GetoptLong.new(
      [SOME_OPTION, '-s', GetoptLong::OPTIONAL_ARGUMENT]
      [HELP_OPTION, '-h', GetoptLong::OPTIONAL_ARGUMENT]
  )
  some_param = nil

  opts.each do |opt, arg|
    case opt
      when SOME_OPTION
        some_param = arg
      when HELP_OPTION
        help
    end
  end

  return some_param
end

def main
  parse_options

  # Some actions
end

if File.identical?(__FILE__, $0)
  main
end

Links