Class: CLI::Prompt

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby/cmd/prompt.rb

Overview

This class contains auto complete functionality TODO: should be refactored to a new module

Instance Method Summary collapse

Constructor Details

#initialize(class_name, prompt = "> ") ⇒ Prompt

Returns a new instance of Prompt.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ruby/cmd/prompt.rb', line 19

def initialize(class_name, prompt = "> ")
  @prompt = prompt
  @class_name = class_name
  @complete_commands = []
  @initial_complete_commands = []

  complete

  Readline.completion_append_character = " "
  Readline.basic_word_break_characters = ""

  Readline.completion_proc = proc do |s|
    s = update_complete_commands! s
    @complete_commands.grep(/^#{Regexp.escape(s)}/)
  end
end

Instance Method Details

#cmd_loopObject



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/ruby/cmd/prompt.rb', line 63

def cmd_loop
  while true
    line = Readline.readline(@prompt, false)
    if line.nil?
      break
    end
    params = line.split
    unless params.empty?
      method_names = @class_name.instance_methods.grep(/^do_#{Regexp.escape(params.shift)}$/)
      unless method_names.empty?
        self.send(method_names[0], params.join(" "))
      end
    end

    if line.to_s.strip != ""
      Readline::HISTORY.push << line
    end
  end
end

#completeObject



36
37
38
39
# File 'lib/ruby/cmd/prompt.rb', line 36

def complete
  @complete_commands = @class_name.instance_methods.grep(/^do_(.*?)$/).map {|s| s.to_s.sub("do_", "")}
  @initial_complete_commands = @class_name.instance_methods.grep(/^do_(.*?)$/).map {|s| s.to_s.sub("do_", "")}
end

#update_complete_commands!(s) ⇒ Object

def complete_git

%w(clone init commit status push)

end



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ruby/cmd/prompt.rb', line 49

def update_complete_commands! s
  args = s.split
  command = args.shift
  method_names = command.nil? ? [] : @class_name.instance_methods.grep(/^complete_#{Regexp.escape(command)}$/)

  if command.nil? or method_names.empty?
    @complete_commands = @initial_complete_commands.clone
  else
    @complete_commands = self.send(method_names[0]).map {|s| "#{command} #{s}"}
  end

  s
end