Module: Dry::CLI::Parser

Defined in:
lib/patches/dry-cli.rb

Overview

Add option value transformation based upon the value of the option’s “type:” parameter.

Constant Summary collapse

TRANSFORMERS =
{
  integer:  -> (v) { v&.to_i },
  float:    -> (v) { v&.to_f }
}

Class Method Summary collapse

Class Method Details

.call(command, arguments, prog_name) ⇒ Object



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/patches/dry-cli.rb', line 202

def self.call(command, arguments, prog_name)
  original_arguments = arguments.dup
  parsed_options = {}

  OptionParser.new do |opts|
    command.options.each do |option|
      opts.on(*option.parser_options) do |value|
        if TRANSFORMERS.has_key?(option.options[:type])
          value = TRANSFORMERS[option.options[:type]].call(value)
        end

        parsed_options[option.name.to_sym] = value
      end
    end

    opts.on_tail("-h", "--help") do
      return Result.help
    end
  end.parse!(arguments)

  parsed_options = command.default_params.merge(parsed_options)
  parse_required_params(command, arguments, prog_name, parsed_options)
rescue ::OptionParser::ParseError
  Result.failure("ERROR: \"#{prog_name}\" was called with arguments \"#{original_arguments.join(" ")}\"") # rubocop:disable Metrics/LineLength
end