Created
September 29, 2009 16:16
-
-
Save automatthew/196983 to your computer and use it in GitHub Desktop.
Pattern for single file lib/script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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