Skip to content

Colorizing Your Bar

Jeff Felchner edited this page Sep 15, 2017 · 6 revisions

Although the generic progressbar is pretty freakin' sweet, it can always be better with a little artistic flair. And one of the best ways to do that is with some colors.

How do you colorize your progressbar you ask? Simple. But first a quick primer on ANSI escape codes for colors.

ANSI Code Primer

In order for your terminal to output colors, it first needs to know that you want to do such a thing. Because all a terminal can respond to are ANSI characters, which is generally just text, a standard was developed to say "when we send through this exact string of characters, interpret them to do something special."

So, in order to tell the terminal to change colors, you need to use the standard set of characters for that. This is the formula:

\e[<brightness>;<color_code>m

In order to reset the color back to "normal", just use 0

\e[0m

brightness is either 0 for dim or 1 for bright, but how do you know what the color codes are?

The color table on the ANSI Escape Codes Wikipedia page shows both the foreground and background color codes for each available color.

Technically you can use not only those 8 colors (and their bright alternates), but also a 256 palette and (if your terminal supports it) a 24-bit (16 million colors) palette. But that is beyond the scope of this article.

For more information, you can visit the ANSI Escape Codes page on Wikipedia.

Using ANSI Codes to Change ruby-progressbar's Colors

Your ANSI color codes can be used inside of your format string just like you would add anything else. So, for example, if you wanted to make your progressbar blue, you'd do the following (Hint: the foreground code for blue is 34):

progressbar = ProgressBar.create(format: "\e[0;34m%t: |%B|\e[0m")

100.times { progressbar.increment; sleep 0.1 }

You'll see something like this:

blue-progressbar-animation

What about if you only wanted to colorize the bar?

progressbar = ProgressBar.create(format: "%t: |\e[0;34m%B\e[0m|", length: 80)

100.times { progressbar.increment; sleep 0.1 }

Now you'll see something like this:

blue-progressbar-animation-with-only-bar-colorized

And because you can change the format for your bar at any time, you can change the color of your bar at any time.

Example

Let's say you're building a script that shows your progressbar as normal when everything is good, but want it to change to red if there's an error.

progressbar = ProgressBar.create(format: "\e[0m%t: |%B|\e[0m")

100.times do |i|
  progressbar.increment

  if i == 72 # Simulate a conditional representing an error
    progressbar.format = "%t: |\e[31m%B\e[0m|"
  end

  sleep 0.1
end

This output would look like this:

simulated-colorized-error

Clone this wiki locally