Class: EpubTools::CLIHelper
- Inherits:
-
Object
- Object
- EpubTools::CLIHelper
- Defined in:
- lib/epub_tools/cli_helper.rb
Overview
A simple helper to DRY CLI OptionParser usage across commands
Class Method Summary collapse
-
.parse(options = {}, required_keys = [], &block) ⇒ Object
Parses ARGV into options hash, enforces required keys, and displays help/errors.
Class Method Details
.parse(options = {}, required_keys = [], &block) ⇒ Object
Parses ARGV into options hash, enforces required keys, and displays help/errors. options: hash of defaults; required_keys: array of symbols required
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/epub_tools/cli_helper.rb', line 8 def self.parse( = {}, required_keys = [], &block) parser = OptionParser.new do |opts| block.call(opts, ) opts.on('-h', '--help', 'Prints this help') { puts opts; exit } end begin parser.parse! unless required_keys.empty? missing = required_keys.select { |k| [k].nil? } unless missing.empty? STDERR.puts "Missing required options: #{missing.map { |k| "--#{k.to_s.gsub('_','-')}" }.join(', ')}" STDERR.puts parser exit 1 end end rescue OptionParser::InvalidOption, OptionParser::MissingArgument => e STDERR.puts e. STDERR.puts parser exit 1 end end |