Skip to content

Instantly share code, notes, and snippets.

@DriftwoodJP
Created May 15, 2014 07:30
Show Gist options
  • Save DriftwoodJP/47251ebcb0403dc166fe to your computer and use it in GitHub Desktop.
Save DriftwoodJP/47251ebcb0403dc166fe to your computer and use it in GitHub Desktop.
ruby で ARGV をうけるコマンドっぽいものを作ってみる | http://www.d-wood.com/blog/2014/05/15_6221.html
#!/usr/bin/ruby
require 'optparse'
# default options
USER = 'Tom'
PASSWORD = 'tomtom'
SERVER = 'localhost'
OPTS = {}
OptionParser.new do |opt|
begin
opt.program_name = File.basename($0)
opt.version = '0.0.1'
opt.banner = "Usage: #{opt.program_name} [options] file.csv"
opt.separator ''
opt.separator 'Examples:'
opt.separator " % #{opt.program_name} -u foo -p bar -s buzz file.csv"
opt.separator ''
opt.separator 'Specific options:'
opt.on('-u USER', '--user', 'user') {|v| OPTS[:u] = v}
opt.on('-p PASSWORD', '--password', 'password') {|v| OPTS[:p] = v}
opt.on('-s SERVER', '--server', 'server') {|v| OPTS[:s] = v}
opt.separator ''
opt.separator 'Common options:'
opt.on_tail('-h', '--help', 'show this help message and exit') do
puts opt
exit
end
opt.on_tail('-v', '--version', 'show program\'s version number and exit') do
puts "#{opt.program_name} #{opt.version}"
exit
end
opt.parse!(ARGV)
rescue => e
puts "ERROR: #{e}.\nSee #{opt}"
exit
end
end
if OPTS[:u] then user = OPTS[:u] else user = USER end
if OPTS[:p] then password = OPTS[:p] else password = PASSWORD end
if OPTS[:s] then server = OPTS[:s] else server = SERVER end
if ARGV[0] then file_name = ARGV[0] else raise 'ERROR: File not found' end
puts "#{server} #{user}:#{password} #{file_name}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment