Class: Luogu::Terminal

Inherits:
Base
  • Object
show all
Defined in:
lib/luogu/terminal.rb

Instance Method Summary collapse

Methods inherited from Base

#config, #logger

Constructor Details

#initialize(desc: "请输入你的指令>") ⇒ Terminal

Returns a new instance of Terminal.



5
6
7
8
9
# File 'lib/luogu/terminal.rb', line 5

def initialize(desc: "请输入你的指令>")
  @desc = desc
  @default_action = nil
  @actions = []
end

Instance Method Details

#action(action_name, &block) ⇒ Object



11
12
13
# File 'lib/luogu/terminal.rb', line 11

def action(action_name, &block)
  @actions << { action_name: action_name, action_method: block }
end

#ask(message) ⇒ Object



36
37
38
# File 'lib/luogu/terminal.rb', line 36

def ask(message)
  TTY::Prompt.new.ask(message)
end

#default(&block) ⇒ Object



15
16
17
# File 'lib/luogu/terminal.rb', line 15

def default(&block)
  @default_action = block
end

#runObject



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

def run
  loop do
    # 从命令行读取输入
    input = ask(@desc).cover_chinese

    if input == 'exit'
      break
    end

    if (action = @actions.find { |h| h[:action_name].to_s == input })
      action.fetch(:action_method)&.call(input)
    else
      @default_action&.call(input)
    end
  end
end