class BusyIndicator

An object of this class indicates activity. It does so asynchronously until interrupted.

Examples:

Attributes

width[W]

Public Class Methods

new(start = true, width = nil, animation = nil, &b) click to toggle source

Constructor. All arguments are optional; set 'start' to true to start immediately, define the width of the output as a number of visible characters. The variable 'animation' can contain an array of symbols which will be printed sequentially to create an animation.

If a block is given, its output will be printed repeatedly, instead of the animation-symbols. In the block, consider protecting shared ressources with a Mutex.

# File lib/busy_indicator.rb, line 83
def initialize(start = true, width = nil, animation = nil, &b)
        
        # @animation = %w"OOO ooo ___ ooo"
        # @animation = %w"||||||| ||||||( |||||(- |||(-)| ||(-)|| |(-)||| (-)|||| -)||||| )|||||"

        @animation = (animation || %w"||| ||| ((( <<< ––– ––– >>> )))")
        @proc = b if b

        l = @animation.max {|a, b| a.length <=> b.length}.length

        @width = (width && width >= l ? width : l)
        @thr = busy_indicator(@width) if start
end

Public Instance Methods

run() click to toggle source

start the animation

# File lib/busy_indicator.rb, line 97
def run() 
        @thr = busy_indicator(@width)
end
stop(comment = nil) click to toggle source

stop the animation and print the comment.

# File lib/busy_indicator.rb, line 101
def stop(comment = nil)
        @thr.terminate
        @thr.join
        print ("\b" * @width)
        print ("%+#{@width}s\n" %comment) if comment
end

Private Instance Methods

animate(width) click to toggle source
# File lib/busy_indicator.rb, line 109
def animate(width)
        # nw = width
        loop do 
                @animation.each do |s|
                        print ("\b" * (width))
                        print "%+#{width}s" %s
                        sleep 0.1
                end
        end
end
busy_indicator( width ) click to toggle source

called by the method run().

# File lib/busy_indicator.rb, line 137
def busy_indicator( width )
        tobj = Thread.new()  do  
                if(@proc)
                        evolve      
                else
                        animate width
                end
        end
end
evolve() click to toggle source
# File lib/busy_indicator.rb, line 120
def evolve
        loop do
                begin
                sv = @proc.call
                if(@width < sv.length)
                        @width += sv.length/2
                end
                print "\b" * @width
                print "%+#{@width}s" %sv
                rescue Exception
                        stop('thread ended abnormally')
                end
                # sleep 0.5
        end
end