Method for formatting HTML nicely?

Anyone who knows a piece of Ruby code that takes a string of HTML as
input and then outputs it nicely formatted like the following?

Before:

Ugly code ...

After:

Ugly code ...

Any suggestions is welcome! Thanks.

Anyone who knows a piece of Ruby code that takes a string of HTML as
input and then outputs it nicely formatted like the following?

You want the tidy library.

http://tidy.rubyforge.org/
http://www.cosinux.org/~dam/projects/rails-tidy/doc/