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