Class: SpinToWin::Spinner

Inherits:
Object
  • Object
show all
Includes:
Celluloid, Celluloid::Notifications
Defined in:
lib/spin_to_win/spinner.rb

Overview

rubocop:disable ClassLength

Constant Summary collapse

LINE_CHARS =
%w(| / - \\).freeze
BRAILLE_CHARS =
%w(⣾ ⣽ ⣻ ⢿ ⡿ ⣟ ⣯ ⣷).freeze
BAR_CHARS =
%w(┤ ┘ ┴ └ ├ ┌ ┬ ┐).freeze
CIRCLE_CHAR =
%w(◐ ◓ ◑ ◒).freeze
SPIN_CHARSET =
{
  line: LINE_CHARS,
  braille: BRAILLE_CHARS,
  bar: BAR_CHARS,
  circle: CIRCLE_CHAR
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(title = nil, charset: :line) ⇒ Spinner

Returns a new instance of Spinner.



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/spin_to_win/spinner.rb', line 39

def initialize(title = nil, charset: :line)
  @title = title
  @charset = SPIN_CHARSET[charset.to_sym]

  subscribe('spinner_increment_todo', :on_increment_todo)
  subscribe('spinner_increment_done', :on_increment_done)
  subscribe('spinner_complete', :on_complete)
  subscribe('spinner_output', :on_output)
  subscribe('spinner_set_banner', :on_set_banner)
  subscribe('spinner_add_banner', :on_add_banner)
  subscribe('spinner_remove_banner', :on_remove_banner)
end

Class Method Details

.with_spinner(title = nil, charset: :line, &blk) ⇒ Object

rubocop:disable UnusedMethodArgument



26
27
28
29
30
31
32
33
34
35
# File 'lib/spin_to_win/spinner.rb', line 26

def with_spinner(title = nil, charset: :line, &blk)
  spinner = Spinner.new(title, charset: charset)
  the_spin = spinner.future.spin
  result = yield(spinner)
  spinner.complete!
  the_spin.value
  $stderr.puts ''
  $stderr.flush
  result
end

Instance Method Details



92
93
94
# File 'lib/spin_to_win/spinner.rb', line 92

def banner(banner)
  @banner_queue = [banner]
end

#complete!Object



84
85
86
# File 'lib/spin_to_win/spinner.rb', line 84

def complete!
  @run = false
end

#increment_done!(count = 1) ⇒ Object



80
81
82
# File 'lib/spin_to_win/spinner.rb', line 80

def increment_done!(count = 1)
  @done_count += count
end

#increment_todo!(count = 1) ⇒ Object



76
77
78
# File 'lib/spin_to_win/spinner.rb', line 76

def increment_todo!(count = 1)
  @todo_count += count
end

#output(msg) ⇒ Object



88
89
90
# File 'lib/spin_to_win/spinner.rb', line 88

def output(msg)
  @log_queue << msg
end

#spin(fps = 12) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/spin_to_win/spinner.rb', line 52

def spin(fps = 12)
  delay = 1.0 / fps
  iteration = previous_msg_size = 0

  init_spinner

  # Keep spinning until told otherwise
  while @run
    output_log

    msg = build_message(iteration += 1)
    previous_msg_size = print_message(msg, previous_msg_size, delay)
  end

  if @todo_count > @done_count
    puts "WARNING: spinner completed with pending jobs #{@done_count} of #{@todo_count}"
  end

  $stderr.print build_message(iteration)
  $stderr.puts ''

  iteration
end