Sha256: 85ace39e04e62576b14c46e76547aa8017c6be45fae58d1edff93d68d896fffd
Contents?: true
Size: 1.44 KB
Versions: 1
Compression:
Stored size: 1.44 KB
Contents
require 'optparse' class EasyOptionParser attr_reader :options, :title def initialize(title, arguments) @options = {} @title = title assert_valid_arguments!(arguments, symbol: :name) assert_valid_arguments!(arguments, symbol: :short) assert_valid_arguments!(arguments, symbol: :long) populate_with_default_values(arguments) parser = OptionParser.new do |opts| opts.banner = @title arguments.each do |argument| long = "#{argument.long} #{argument.name}" description = (argument.required) ? "#{argument.description} *" : argument.description opts.on(argument.short, long, description) do |value| options[argument.name.to_sym] = value end end opts.on('-h', '--help', 'Displays Help') do puts opts exit end end parser.parse! end def contains?(name) @options.include?(name.to_sym) end private def assert_valid_arguments!(arguments, symbol:) raise 'Arguments cannot be nil' if arguments.nil? raise 'Arguments cannot be empty' if arguments.empty? raise 'Arguments must be an Array' unless arguments.is_a?(Array) argument_names = arguments.map(&symbol) raise 'Duplicated value in options' if argument_names.detect{|a| argument_names.count(a) > 1} end def populate_with_default_values(arguments) arguments.each do |argument| @options[argument.name.to_sym] = argument.default_value end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
easy_opt_parser-0.0.1 | lib/easy_opt_parser.rb |