Class: Rixie::CLI::Spinner

Inherits:
Object
  • Object
show all
Defined in:
lib/rixie/cli/spinner.rb

Constant Summary collapse

FRAMES =
%w[         ].freeze

Instance Method Summary collapse

Constructor Details

#initialize(terminal:, prefix:, io: $stdout) ⇒ Spinner

Returns a new instance of Spinner.



8
9
10
11
12
13
14
15
# File 'lib/rixie/cli/spinner.rb', line 8

def initialize(terminal:, prefix:, io: $stdout)
  @terminal = terminal
  @prefix = prefix
  @io = io
  @mutex = Mutex.new
  @stopped = true
  @thread = nil
end

Instance Method Details

#startObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rixie/cli/spinner.rb', line 17

def start
  return self unless stopped?

  @mutex.synchronize { @stopped = false }
  @thread = Thread.new do
    i = 0
    loop do
      break if @mutex.synchronize { @stopped }
      @io.print "\r#{@prefix}#{@terminal.accent(FRAMES[i % FRAMES.size])} Thinking..."
      @io.flush
      i += 1
      sleep 0.08
    end
  end
  self
end

#stopObject



34
35
36
37
38
39
40
# File 'lib/rixie/cli/spinner.rb', line 34

def stop
  return if stopped?
  @mutex.synchronize { @stopped = true }
  @thread&.join
  @io.print "\r#{@prefix}#{" " * 20}\r#{@prefix}"
  @io.flush
end

#stopped?Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/rixie/cli/spinner.rb', line 42

def stopped?
  @mutex.synchronize { @stopped }
end