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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Freezing lookup constants keeps shared configuration data immutable and safe to reuse.
- 2Detecting a TTY before emitting escape codes keeps output clean when piped or redirected.
- 3Defining methods from a data table gives you a whole DSL without writing each method by hand.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
ruby
class SnippetHighlighter CONTEXT_RADIUS = 60 MAX_TERMS = 8
Building search-result snippets in Ruby
regular-expressions
text-processing
search
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-an-ansi-color-dsl-in-ruby-explained-ruby-5871/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.