Skip to content

Instantly share code, notes, and snippets.

@automatthew
Created September 29, 2009 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save automatthew/196983 to your computer and use it in GitHub Desktop.
Save automatthew/196983 to your computer and use it in GitHub Desktop.
Pattern for single file lib/script
#!/usr/bin/env ruby
#
# Simple pattern for a Ruby script where the command line processing
# is done separately from the rest of the code. This allows the file
# to be required by other Ruby code without acting as an executable.
class Project
# Defaults to be overridden by command line options
DefaultHost = "localhost"
# Hard-coded configuration, unlikely to change with each invocation
ConfigValue = "q"
def initialize(file1, file2, options)
@file1, @file2 = file1, file2
@options = options
@options[:host] ||= DefaultHost
raise ArgumentError, "No such file: #{@query_file}" unless File.file?(@query_file)
end
def run
# Do something clever.
end
end
# The following runs only when this file is executed.
if $PROGRAM_NAME == __FILE__
require 'optparse'
usage = "Usage: botch.rb [-v] [-h HOST] query_file bval kval"
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: botch.rb [-d] query_file bval kval"
opts.on("-v", "--verbose", "Verbose output") do |verbose|
options[:verbose] = verbose
end
opts.on("-h", "--host HOST", "The host--") do |host|
options[:host] = host
end
end.parse!
# OptionParser is kind enough to delete its opts from ARGV for us
file1, file2 = *ARGV
puts usage and exit unless file2 && file2
project = Project.new(file1, file2, options)
project.run
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment