Last active
June 3, 2023 03:16
-
-
Save rtomayko/1190547 to your computer and use it in GitHub Desktop.
Ruby optparse template
This file contains 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 | |
#/ Usage: <progname> [options]... | |
#/ How does this script make my life easier? | |
# ** Tip: use #/ lines to define the --help usage message. | |
$stderr.sync = true | |
require 'optparse' | |
# default options | |
flag = false | |
option = "default value" | |
integer = 23 | |
list = ["x", "y", "z"] | |
# parse arguments | |
file = __FILE__ | |
ARGV.options do |opts| | |
opts.on("-f", "--flag") { flag = true } | |
opts.on("-o", "--opt=val", String) { |val| option = val } | |
opts.on("-i", "--int=val", Integer) { |val| integer = val } | |
opts.on("--list=[x,y,z]", Array) { |val| list = val } | |
opts.on_tail("-h", "--help") { exec "grep ^#/<'#{file}'|cut -c4-" } | |
opts.parse! | |
end | |
# do your thing | |
warn "ARGV: #{ARGV.inspect}" | |
warn "flag: #{flag.inspect}" | |
warn "option: #{option.inspect}" | |
warn "integer: #{integer.inspect}" | |
warn "list: #{list.join(',')}" |
Can you explain the # ** Tip: use #/ lines to define the --help usage message.
comment? What does #/
do?
Nevermind: I see that line 21 calls out to grep
and cut
to parse the program.
opts.on_tail("-h", "--help") { exec "grep ^#/<'#{file}'|cut -c4-" }
Why not use pure ruby or the built-in help from opt-parse?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome! I've been using the template from the end of your shell hater's presentation. Adding this one to my tool belt.