Skip to content

Instantly share code, notes, and snippets.

@KINGSABRI
Created June 1, 2021 18:30
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 KINGSABRI/b38f6b4a367cae670f0a174fdb146322 to your computer and use it in GitHub Desktop.
Save KINGSABRI/b38f6b4a367cae670f0a174fdb146322 to your computer and use it in GitHub Desktop.
Ruby optparse example
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'mail', require: 'mail'
gem 'json', require: 'json'
gem 'optparse', require: true
gem 'ostruct', require: true
end
opt = OpenStruct.new(
server: nil, user: nil, pass: nil
)
option_parser = OptionParser.new do |opts|
opts.banner = "A simple email sender"
opts.separator ""
opts.separator "Help menu:"
opts.on("-s", "--server HOST:PORT", "SMTP server and its port.", "\te.g. smtp.office365.com:587") do |o|
opt.server = o
end
opts.on("-u", "--user USER", "Username to authenticate.", "\te.g. user@domain.com") do |o|
opt.user = o
end
opts.on("-p", "--pass PASS", "Password to authenticate") do |o|
opt.pass = o
end
opts.on("-h", "--help", "Show this message.") do
puts logo
puts opts
exit!
end
opts.on_tail "\nUsage:\n" + " #{File.basename(__FILE__)} <OPTIONS>"
opts.on_tail "Example:"
opts.on_tail %{ $#{File.basename(__FILE__)} -s smtp.office365.com:587 -u user1@domain.com -p P@ssword1\n\n}
end
begin
pp option_parser.parse!(ARGV)
rescue OptionParser::MissingArgument => e
puts option_parser
e.args.each {|arg| puts '[!] '+ "#{e.reason.capitalize} for '#{arg}' option."}
rescue OptionParser::InvalidOption => e
puts option_parser
pp e
rescue Exception => e
puts "#{$PROGRAM_NAME} Exception".error
puts e.backtrace_locations
puts e
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment