DEV Community

Chaitali Khangar
Chaitali Khangar

Posted on

Colorful Text in Rails with ANSI Escape Codes

Ever wonder about how Rails produces those vibrant, colorful displays for RSpec and Logger?

Take a look at this piece of Ruby code:

puts "\e[32mHi"
Enter fullscreen mode Exit fullscreen mode

🧐 'Hi' appears in dazzling green.

Here's the magic behind it: ANSI escape codes.

These codes were cleverly designed in programming languages to provide developers with a standardized way to control the format and appearance of text in terminal/console output.

When do we use this?

1️⃣ Enhanced Readability: ANSI escape codes make text more readable by allowing developers to change colors, styles, and backgrounds, ensuring that important information stands out.

2️⃣ Visual Feedback: These mystical codes offer visual cues to users, from progress bars to color-coded status updates.

3️⃣ Debugging and Logging: They help format debugging and logging messages, enabling developers to quickly identify the severity of issues based on text appearance.

4️⃣ Interactive Interfaces: ANSI escape codes make command-line applications more interesting by allowing them to create interactive user interfaces.

Where does Rails work its magic with these codes?

  • RSpec
  • Logger's Colorful Logs
  • Colorful Console Output

Image description

Here is the bonus:

If you want to check where ANSI code exists in Rails feel free to reach out:

https://github.com/rails/rails/blob/6c9967f85ada90f8ca58e794a850e887ceb45132/activesupport/lib/active_support/log_subscriber.rb#L76

https://github.com/rspec/rspec-core/blob/1c662c35f91f33946fdfbed431878f4798f06f70/lib/rspec/core/formatters/console_codes.rb#L47

Till we meet next time. Happy Coding!!

Top comments (0)