class ArgParser

Public Class Methods

parse(args) click to toggle source

Returns a structure describing the options.

# File lib/argparser.rb, line 52
def self.parse(args)
  # The options specified on the command line will be collected in <b>options</b>.
  # We set default values here.
  options = OpenStruct.new
  options.qualify = false
  options.color = 'white'
  options.list = false
  options.add = nil

  op = OptionParser.new do |opts|
    opts.banner = trl("Usage") << ":\t" << "%s <options>" %($0) <<"\n"

    opts.separator ""
    opts.separator trl("Specific options") << ":"

    opts.on('-' << trl('a'), '--' << trl('add') , trl('Add real proverb to the base') ) do |g|
      options.add = g
    end

    opts.on('-' << trl('f'), '--' << trl('favorites'), trl('Show favorites')) do
      options.list = true
    end

    opts.on('-' << trl('q'), '--' << trl("qualify"), trl("Qualify proverbs")) do 
      options.qualify = true
    end

    opts.on('-' << trl('c'), '--' << trl('color') << '=' << trl('COLOR'), trl('Use color in program-output (one of red, green, yellow, purple, cyan, blue, white, black)')) do |col|
      color = trl_color(col.strip) 
      if(color && [:red, :green, :yellow, :purple, :cyan, :blue, :white, :black].include?(color.strip.to_sym))
        options.color = color
      else
        puts (trl("Error!") << ' ' << trl('Invalid color value') << ' "' << col << '"!')
        usage()
        exit false
      end
    end

    opts.separator ""
    opts.separator (trl("Common options")) << ':'

    # No argument, shows at tail.  This will print an options summary.
    opts.on_tail('-' << trl('h'), '--' << trl('help'), (trl('Show this message') ) ) do
      usage(opts)
    end

    opts.on_tail('-' << trl('v'), '--' << trl('version'), (trl('Show version and program information') )) do
      puts "\t#{$0} #{VERSION}"
      puts "\t© 2016-2019 Michael Uplawski <michael.uplawski at uplawski.eu>"
      exit true
    end
  end
  begin
    op.parse!(args)
  rescue OptionParser::MissingArgument => ex
    puts trl(ex.reason) + " " << trl("for option") << " " << ex.args[0] 
    usage()
    exit
  rescue OptionParser::InvalidOption => ex
    puts trl(ex.reason) + " " << ex.args[0] 
    usage()
    exit
  end
  options
end
trl_color(localized_color) click to toggle source
# File lib/argparser.rb, line 35
def self.trl_color(localized_color)
  color = %w~
        red
        green
        purple
        yellow
        cyan
        blue
        white
        black
  ~.detect {|col| trl(col) == localized_color }
  return color
end
usage(opts = nil) click to toggle source
# File lib/argparser.rb, line 118
def self::usage(opts = nil)
  if(opts)
    puts opts
  else
    puts trl("Execute with option -h to see an option summary")
  end
  exit true

end