Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Autocompletion of OptionParser Flags in Ruby

Tags:

ruby

#!/usr/bin/env ruby

require 'optparse'

options = {}
OptionParser.new do |opts|
  opts.on("--language LANGUAGE", ["Ruby", "JavaScript"]) do |language|
    options[:language] = language
  end 
end.parse!

puts "Language: #{options[:language]}"

If I run this w/ ./bin/example --language Ru it will output:

Language: Ruby

I would like the disable this autocomplete/closest match behavior and have OptionParser raise when the exact name is not provided however I do not see a way to do this from their documentation.

Any ideas?

like image 698
Kyle Decot Avatar asked Apr 03 '19 18:04

Kyle Decot


1 Answers

the search settings are defined in self.regexp

the method complete seems to return all the different flags.

The method self.regexp defines the search query used

class OptionParser
  module Completion
    def self.regexp(key, icase)
      Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'), icase)
    end
  end
end

The regex is built with the following flags

\A search from the beginning of the string

\w* search any of the matching characters

the candidate iterates using a method object &method(:each) passed as a proc with &. The method object is called on Completion class.

candidates = candidate(key, icase, pat, &method(:each)).sort_by {|k, v, kn| kn.size}

the block iterates inside self.candidate

def self.candidate(key, icase = false, pat = nil, &block)
  pat ||= Completion.regexp(key, icase)
  candidates = []
  block.call do |k, *v|
    // Search and add candidates
  end
  candidates
end

The iterator run the following check for each entry. I still don't have 100% understanding of this check, responsible for finding the flags.

block.call do |k, *v|
  (if Regexp === k
     kn = ""
     k === key
   else
     kn = defined?(k.id2name) ? k.id2name : k
     pat === kn
   end) or next
  v << k if v.empty?
  candidates << [k, v, kn]
end
candidates
like image 122
Fabrizio Bertoglio Avatar answered Oct 06 '22 00:10

Fabrizio Bertoglio