Class: RubyRich::ProgressManager

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_rich/progress_manager.rb

Defined Under Namespace

Classes: Handle

Constant Summary collapse

FRAMES =
%w[| / - \\].freeze

Instance Method Summary collapse

Constructor Details

#initialize(on_change: nil) ⇒ ProgressManager

Returns a new instance of ProgressManager.



54
55
56
57
58
59
60
61
# File 'lib/ruby_rich/progress_manager.rb', line 54

def initialize(on_change: nil)
  @stack = []
  @mutex = Mutex.new
  @on_change = on_change
  @frame = 0
  @ticker = nil
  @running = false
end

Instance Method Details

#currentObject



98
99
100
# File 'lib/ruby_rich/progress_manager.rb', line 98

def current
  @mutex.synchronize { @stack.last }
end

#finish(id, owner, state, message) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/ruby_rich/progress_manager.rb', line 83

def finish(id, owner, state, message)
  ok = @mutex.synchronize do
    handle = @stack.find { |item| item.id == id && item.owner == owner }
    next false unless handle

    handle.instance_variable_set(:@state, state)
    handle.instance_variable_set(:@message, message.to_s)
    @stack.delete(handle)
    true
  end
  notify if ok
  stop_ticker_if_idle
  ok
end

#renderObject



102
103
104
105
106
107
108
# File 'lib/ruby_rich/progress_manager.rb', line 102

def render
  handle = current
  return nil unless handle

  frame = FRAMES[@frame % FRAMES.length]
  "#{frame} #{handle.message}"
end

#start(message, owner: Thread.current.object_id) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/ruby_rich/progress_manager.rb', line 63

def start(message, owner: Thread.current.object_id)
  handle = Handle.new(self, id: SecureRandom.hex(6), owner: owner, message: message.to_s)
  @mutex.synchronize { @stack << handle }
  start_ticker
  notify
  handle
end

#update(id, owner, message) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/ruby_rich/progress_manager.rb', line 71

def update(id, owner, message)
  ok = @mutex.synchronize do
    handle = @stack.find { |item| item.id == id && item.owner == owner && item.active? }
    next false unless handle

    handle.instance_variable_set(:@message, message.to_s)
    true
  end
  notify if ok
  ok
end

#with_progress(message) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/ruby_rich/progress_manager.rb', line 110

def with_progress(message)
  handle = start(message)
  begin
    yield handle
    handle.finish
  rescue Exception => e
    handle.fail(e.message)
    raise
  ensure
    handle.cancel if handle.active?
  end
end