Class: TinyBar

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

Overview

the TinyBar class is used to create a text-based progress bar with various properties like width, background color, foreground color, label, and percent filled.

usage:

tiny_bar = TinyBar.new           # creates a new TinyBar instance
tiny_bar.label = 'Progress'      # sets the label to 'Progress'
tiny_bar.percent_filled = 0.5    # sets the percent filled to 50%
tiny_bar.width = 100             # sets the width of the bar to 100
tiny_bar.bg_color = :blue        # sets the background color to blue
tiny_bar.fg_color = :white       # sets the foreground color to white
puts tiny_bar                    # prints the TinyBar instance

This will print a progress bar of width 100 with a blue background, white foreground, and ‘Progress’ label filled to 50%.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTinyBar

Returns a new instance of TinyBar.



26
27
28
29
30
31
32
33
# File 'lib/tiny_bar.rb', line 26

def initialize
  @width = 80
  @bg_color = :default
  @fg_color = :default
  @label = ''
  @value = 0
  @percent_filled = 0.0
end

Instance Attribute Details

#bg_colorObject

Returns the value of attribute bg_color.



22
23
24
# File 'lib/tiny_bar.rb', line 22

def bg_color
  @bg_color
end

#fg_colorObject

Returns the value of attribute fg_color.



22
23
24
# File 'lib/tiny_bar.rb', line 22

def fg_color
  @fg_color
end

#labelObject

Returns the value of attribute label.



19
20
21
# File 'lib/tiny_bar.rb', line 19

def label
  @label
end

#percent_filledObject

Returns the value of attribute percent_filled.



19
20
21
# File 'lib/tiny_bar.rb', line 19

def percent_filled
  @percent_filled
end

#widthObject

Returns the value of attribute width.



22
23
24
# File 'lib/tiny_bar.rb', line 22

def width
  @width
end

Instance Method Details

#to_sObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/tiny_bar.rb', line 43

def to_s
  full_width_s = label
    .to_s
    .rjust((width / 2) + (label.length / 2))
    .ljust(width)

  filled_width = (full_width_s.length * percent_filled).round
  unfilled_width = (full_width_s.length - filled_width) - 1

  left = full_width_s[..filled_width]
  right = unfilled_width > 0 ? full_width_s[-unfilled_width..] : ''

  "#{left.send(fg_color).send("on_#{bg_color}")}#{right}"
end