Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
CGI::Util#pretty
(::string string, ?::String shift) -> ::String
pretty(string, shift = " ")
lib/cgi/util.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.4.1/lib/cgi/util.rb, line 246
def pretty(string, shift = " ")
lines = string.gsub(/(?!\A)<.*?>/m, "\n\\0").gsub(/<.*?>(?!\n)/m, "\\0\n")
end_pos = 0
while end_pos = lines.index(/^<\/(\w+)/, end_pos)
element = $1.dup
start_pos = lines.rindex(/^\s*<#{element}/i, end_pos)
lines[start_pos ... end_pos] = "__" + lines[start_pos ... end_pos].gsub(/\n(?!\z)/, "\n" + shift) + "__"
end
lines.gsub(/^((?:#{Regexp::quote(shift)})*)__(?=<\/?\w)/, '\1')
end
Prettify (indent) an HTML string.
string is the HTML string to indent. shift is the indentation unit to use; it defaults to two spaces.
Example
print CGI.pretty("<HTML><BODY></BODY></HTML>") # <HTML> # <BODY> # </BODY> # </HTML> print CGI.pretty("<HTML><BODY></BODY></HTML>", "\t") # <HTML> # <BODY> # </BODY> # </HTML>