CSS Minify & Beautify — Ruby source
Minify CSS (strip comments and whitespace, shorten hexes and decimals) or beautify it back to readable one-declaration-per-line form. Strings stay intact. Runs locally with a shareable link.
This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.
# css-minify — CSS minifier & beautifier. Ruby port (canonical TS:
# src/lib/css-minify.ts; Go twin: cli/css-minify). One scanner masks string
# literals as "\x00n\x00" sentinels and drops /* */ comments; every textual
# rule then runs on the masked text with regexes carrying no lookaround
# (backreferences are Onigmo-supported; \z anchors the absolute end where
# the TS uses $) so the Go twin reproduces byte-identical output. minify —
# collapse whitespace, strip spaces around {} ; : , > (sibling + and ~
# combinators keep theirs), drop the last semicolon before }, lowercase
# hexes, shorten #aabbcc → #abc (never 8-digit alpha), strip leading zeros
# (0.5 → .5) and trailing fraction zeros (1.50 → 1.5, 1.00 → 1, .00 → 0).
# beautify — one selector per block, one declaration per line at 2-space
# depth, each declaration keeping its own semicolon. Errors travel in
# result[:error] (nil = success); empty input is a successful empty output,
# never an error.
module CssMinify
module_function
# JS-style trim: ASCII whitespace only, never \x00 (Ruby's strip would
# eat the trailing sentinel NUL and break unmasking).
def js_trim(s)
s.gsub(/\A[ \t\n\v\f\r]+|[ \t\n\v\f\r]+\z/, '')
end
HEX_LOWER = /#[0-9a-fA-F]{3,8}/
HEX_PAIR = /#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3([^0-9a-f]|\z)/
LEADING_ZERO = /(^|[^A-Za-z0-9_.#$%-])0+(\.[0-9]+)/
FRACTION_ZEROS = /(\.[0-9]*[1-9])0+([^0-9]|\z)/
INTEGRAL_ZEROS = /(^|[^A-Za-z0-9_.#$%-])([0-9]+)\.0+([^0-9]|\z)/
DOT_ZEROS = /(^|[^A-Za-z0-9_.#$%-])\.0+([^0-9]|\z)/
# Scan CSS into [masked, strings]; mask every string literal as a
# "\x00n\x00" sentinel and drop /* */ comments. err is non-nil on failure.
def mask(raw)
out = +''
strings = []
i = 0
n = raw.length
while i < n
ch = raw[i]
if ch == '"' || ch == "'"
start = i
i += 1
while i < n && raw[i] != ch
i += 2 if raw[i] == '\\' && i + 1 < n # escaped char
i += 1
end
return [nil, nil, 'Unterminated string'] if i >= n
i += 1
strings << raw[start...i]
out << "\x00#{strings.size - 1}\x00"
elsif ch == '/' && i + 1 < n && raw[i + 1] == '*'
close = raw.index('*/', i + 2)
return [nil, nil, 'Unterminated comment'] if close.nil?
i = close + 2
else
out << ch
i += 1
end
end
[out, strings, nil]
end
def unmask(text, strings)
text.gsub(/\x00(\d+)\x00/) { strings[Regexp.last_match(1).to_i] }
end
# Conservative minification — see the header for the exact rule list.
def minify(raw)
text = js_trim(raw)
return { output: '', error: nil } if text.empty?
masked, strings, err = mask(text)
return { output: '', error: err } if err
css = masked.gsub(/\s+/, ' ')
css = css.gsub(/\s*([{};:,>])\s*/, '\1')
css = css.gsub(/;+}/, '}')
css = js_trim(css)
css = css.gsub(HEX_LOWER, &:downcase)
css = css.gsub(HEX_PAIR) { '#' + $1 + $2 + $3 + $4 }
css = css.gsub(LEADING_ZERO) { $1 + $2 }
css = css.gsub(FRACTION_ZEROS) { $1 + $2 }
css = css.gsub(INTEGRAL_ZEROS) { $1 + $2 + $3 }
css = css.gsub(DOT_ZEROS) { $1 + '0' + $2 }
{ output: unmask(css, strings), error: nil }
end
# Structural beautifier — 2-space indentation, declarations one per line.
def beautify(raw)
text = js_trim(raw)
return { output: '', error: nil } if text.empty?
masked, strings, err = mask(text)
return { output: '', error: err } if err
css = masked.gsub(/\s+/, ' ')
out = +''
buffer = +''
depth = 0
flush = lambda do |semi|
decl = js_trim(buffer)
out << (' ' * depth) << decl << (semi ? ';' : '') << "\n" unless decl.empty?
buffer.clear
end
css.each_char do |ch|
case ch
when '{'
sel = js_trim(buffer)
buffer.clear
return { output: '', error: 'Block without a selector' } if sel.empty?
out << (' ' * depth) << sel << " {\n"
depth += 1
when '}'
flush.call(false)
depth -= 1
return { output: '', error: 'Unbalanced }' } if depth.negative?
out << (' ' * depth) << "}\n"
when ';'
flush.call(true)
else
buffer << ch
end
end
return { output: '', error: 'Unclosed block' } if depth != 0
flush.call(false)
{ output: unmask(out, strings), error: nil }
end
end
# Example:
# CssMinify.minify('body { color : #AABBCC; margin : 0.50px; }')[:output]
# → 'body{color:#abc;margin:.5px}'
# CssMinify.beautify('a{b:c}')[:output] → "a {\n b: c;\n}\n"
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →