ruby 49 lines · 9 steps

Building an ANSI color DSL in Ruby

A module maps color names to ANSI codes, then monkey-patches String so any text can paint itself.

Explained by highlit
1module Terminal
2 module Color
3 CODES = {
4 black: 30, red: 31, green: 32, yellow: 33,
5 blue: 34, magenta: 35, cyan: 36, white: 37,
6 bright_black: 90, bright_red: 91, bright_green: 92,
7 bright_yellow: 93, bright_blue: 94
8 }.freeze
9 
10 STYLES = { bold: 1, dim: 2, italic: 3, underline: 4 }.freeze
11 
12 RESET = "\e[0m"
13 
14 module_function
15 
16 def paint(text, fg: nil, bg: nil, style: nil)
17 return text unless tty?
18 
19 params = []
20 params << STYLES.fetch(style) if style
21 params << CODES.fetch(fg) if fg
22 params << CODES.fetch(bg) + 10 if bg
23 return text if params.empty?
24 
25 "\e[#{params.join(';')}m#{text}#{RESET}"
26 end
27 
28 def tty?
29 $stdout.tty? && ENV['NO_COLOR'].nil?
30 end
31 end
32end
33 
34CODES = Terminal::Color::CODES
35CODES.each_key do |name|
36 String.define_method(name) do
37 Terminal::Color.paint(self, fg: name)
38 end
39end
40 
41%i[bold dim italic underline].each do |style|
42 String.define_method(style) do
43 Terminal::Color.paint(self, style: style)
44 end
45end
46 
47String.define_method(:on) do |color|
48 Terminal::Color.paint(self, bg: color)
49end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Freezing lookup constants keeps shared configuration data immutable and safe to reuse.
  2. 2Detecting a TTY before emitting escape codes keeps output clean when piped or redirected.
  3. 3Defining methods from a data table gives you a whole DSL without writing each method by hand.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building an ANSI color DSL in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code