Skip to content

Instantly share code, notes, and snippets.

@rwilcox
Last active October 4, 2023 21:14
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 rwilcox/657b771f127502d7515d74d615f7bf24 to your computer and use it in GitHub Desktop.
Save rwilcox/657b771f127502d7515d74d615f7bf24 to your computer and use it in GitHub Desktop.
My starter template for creating scripts with lots of parameters that also prompt you to fill out the missing parameters
#!/usr/bin/env ruby
# Why not bash?
# bash is annoying for opts handling
# AND especially annoying if those opts need to be in both --key value AND --key=value format
# AND not DRY.
# and Ruby is pretty close to bash in syntax. Or it's close to Perl, which is close to Bash
# and Python feels like a bunch of boilerplate here
require 'optparse'
# WRITING YOUR OWN SCRIPT? NEED ANY ENV VARS THAT NEED DEFAULT VALUES?
# SET THEM UP HERE, LIKE SO
# ENV['DEFAULT'] = 'BAR'
# monkeypatch this because we're not using ActiveSupport
# but kinda really want to for this one thing, although I think
# in ActiveSupport it's .blank?
class NilClass
def empty?
true
end
end
def or_prompt(var_name, text)
if ENV[var_name].empty?
print text
ENV[var_name] = STDIN.gets.chomp
end
return ENV[var_name]
end
def main
option_parser = OptionParser.new do |opts|
opts.banner = "Usage: ADD USAGE INFORMATION HERE!!!"
# WRITING YOUR OWN SCRIPT? GREAT, ADD PARAMETERS HERE AS YOU NEED
# opts.on[=blah] means you can pass --graph=bar OR --graph bar and it works the same
opts.on("--parameter[=LABEL]", "help text") { |value| ENV["ENV_VALUE_TO_SET"] = value }
opts.on_tail('--help', 'Display help message') do
puts opts
puts "\nWELCOME TO MY SCRIPT"
exit
end
end
option_parser.parse!
# WRITING YOUR OWN SCRIPT? NOW ADD PROMPTS DOWN HERE IF YOU WANT TO ASK ABOUT UNPROVIDED PARAMETERS
or_prompt('ENV_VALUE_TO_SET', "Please provide a value for --parameter (ie SAMPLE): ")
# WRITING YOUR OWN SCRIPT? NOW JUST DRAW THE REST OF THE FUN OWL BELOW!
# NOTE THAT IF YOU SET ANY ENV VARIABLES THEY WILL BE SET FOR PROCESSES SPAWNED
# VIA IE SYSTEM
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment