Class: Shelley::InteractiveShell

Inherits:
Object
  • Object
show all
Defined in:
lib/shelley/shells.rb

Overview

An interactive shell, supporting history and autocompletion

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command_registry) ⇒ InteractiveShell

Returns a new instance of InteractiveShell.



6
7
8
9
# File 'lib/shelley/shells.rb', line 6

def initialize(command_registry)
  @command_registry = command_registry
  @prompt = '> '
end

Instance Attribute Details

#promptObject

Returns the value of attribute prompt.



4
5
6
# File 'lib/shelley/shells.rb', line 4

def prompt
  @prompt
end

Instance Method Details

#autocomplete(line) ⇒ Object

Tries to autocomplete a lines



23
24
25
# File 'lib/shelley/shells.rb', line 23

def autocomplete(line)
  candidate_nodes(*line.split).map(&:name).sort
end

#candidate_nodes(*path) ⇒ Object

Retrieves candidate nodes for a given path



12
13
14
15
16
17
18
19
20
# File 'lib/shelley/shells.rb', line 12

def candidate_nodes(*path)
  return @command_registry.commands_tree.children if path.count.zero?
  last_name = path.pop
  node = @command_registry.commands_tree.node_by_path(*path)
  return [] if node.nil?
  last_node = node.node_by_path(last_name)
  return last_node.children unless last_node.nil?
  node.children.select { |n| n.name =~ /^#{Regexp.escape(last_name)}/ }
end

#startObject

Starts the shell



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/shelley/shells.rb', line 28

def start
  Readline.completion_append_character = ' '
  Readline.completion_proc = lambda do |_line|
    autocomplete(Readline.line_buffer)
  end
  while (line = Readline.readline(@prompt, true))
    begin
      @command_registry.execute_command(line)
    rescue StandardError => msg
      puts msg
    end
  end
end