Class: RS::UI

Inherits:
Object
  • Object
show all
Defined in:
lib/rs/ui.rb

Overview

Readline-based console UI.

Constant Summary collapse

DefaultPrompt =

Default prompt is unexciting.

lambda { "#{Dir.pwd} rs> " }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial_prompt = DefaultPrompt) {|_self| ... } ⇒ UI

UI is set up and prepared to be read/written.

Initial prompt may be given as an argument, and can later be changed using #prompt=.

Yields:

  • (_self)

Yield Parameters:

  • _self (RS::UI)

    the object that the method was called on



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rs/ui.rb', line 48

def initialize(initial_prompt = DefaultPrompt)
  $stdin.sync   = true
  $stdout.sync  = true
  $stderr.sync  = true

  # Work around Readline binding to get full line of input
  Readline.completer_word_break_characters  = 0.chr   # NUL byte unlikely?
  Readline.completion_append_character      = nil

  self.prompt = initial_prompt

  yield self
end

Instance Attribute Details

#promptObject

Prompt used for next input read.



64
65
66
# File 'lib/rs/ui.rb', line 64

def prompt
  @prompt
end

Instance Method Details

#on_input(&block) ⇒ Object

Block to call with each line of input.



81
# File 'lib/rs/ui.rb', line 81

def on_input(&block); @input = block; end

#on_SIGINT(&block) ⇒ Object

^C, keyboard interrupt.



74
# File 'lib/rs/ui.rb', line 74

def on_SIGINT(&block); @sigint = block; end

#puts(data) ⇒ Object

Write #to_s to output.

TODO: Probably need a .print version, huh? –rue



88
89
90
# File 'lib/rs/ui.rb', line 88

def puts(data)
  $stdout.puts data.to_s
end

#runObject

Input loop.

Calls the block given in #on_input for each line of input, as well as any other #on_* handlers as needed.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/rs/ui.rb', line 97

def run()
  loop {
    begin
      if input = Readline.readline(@prompt.call, true)
        @input.call input.chomp
      else
        puts ""
        return
      end
    rescue Interrupt
      @sigint.call
    end
  }
end