Module: Toys::Completion

Defined in:
lib/toys/completion.rb

Overview

A Completion is a callable Proc that determines candidates for shell tab completion. You pass a Context object (which includes the current string fragment and other information) and it returns an array of candidates, represented by Candidate objects, for completing the fragment.

A useful method here is the class method Completion.create which takes a variety of inputs and returns a suitable completion Proc.

Defined Under Namespace

Classes: Base, Candidate, Context, Enum, FileSystem

Constant Summary collapse

EMPTY =

An instance of the empty completion that returns no candidates.

Returns:

  • (Toys:::Completion::Base)
Base.new

Class Method Summary collapse

Class Method Details

.create(spec = nil, **options, &block) ⇒ Toys::Completion::Base, Proc

Create a completion Proc from a variety of specification formats. The completion is constructed from the given specification object and/or the given block. Additionally, some completions can take a hash of options.

Recognized specs include:

  • :empty: Returns the empty completion. Any block or options are ignored.

  • :file_system: Returns a completion that searches the current directory for file and directory names. You may also pass any of the options recognized by Toys::Completion::FileSystem#initialize. The block is ignored.

  • An Array of strings. Returns a completion that uses those values as candidates. You may also pass any of the options recognized by Toys::Completion::Enum#initialize. The block is ignored.

  • A function, either passed as a Proc (where the block is ignored) or as a block (if the spec is nil). The function must behave as a completion object, taking Context as the sole argument, and returning an array of Candidate.

  • :default and nil indicate the default completion. For this method, the default is the empty completion (i.e. these are synonyms for :empty). However, other completion resolution methods might have a different default.

Parameters:

  • spec (Object) (defaults to: nil)

    See the description for recognized values.

  • options (Hash)

    Additional options to pass to the completion.

  • block (Proc)

    See the description for recognized forms.

Returns:



411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/toys/completion.rb', line 411

def self.create(spec = nil, **options, &block)
  if spec.is_a?(::Hash)
    options = options.merge(spec)
    spec = nil
  end
  spec ||= options.delete(:"") || block
  case spec
  when nil, :empty, :default
    EMPTY
  when ::Proc, Base
    spec
  when ::Array
    Enum.new(spec, **options)
  when :file_system
    FileSystem.new(**options)
  when ::Class
    spec.new(**options)
  else
    if spec.respond_to?(:call)
      spec
    else
      raise ToolDefinitionError, "Illegal completion spec: #{spec.inspect}"
    end
  end
end