Class: EpubTools::CLIHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/epub_tools/cli_helper.rb

Overview

A simple helper to DRY CLI OptionParser usage across commands

Class Method Summary collapse

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(options = {}, required_keys = [], &block)
  parser = OptionParser.new do |opts|
    block.call(opts, options)
    opts.on('-h', '--help', 'Prints this help') { puts opts; exit }
  end
  begin
    parser.parse!
    unless required_keys.empty?
      missing = required_keys.select { |k| options[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.message
    STDERR.puts parser
    exit 1
  end
  options
end