Monday, November 26, 2007

Formatting Ruby source code in HTML

BTW, I used the syntax library to format the Ruby source code snippets to HTML. It works like this:

require 'rubygems'
require 'syntax/convertors/html'

code = File.read("my_nifty_program.rb")
convertor = Syntax::Convertors::HTML.for_syntax "ruby"
code_html = convertor.convert( code )
print code_html

You'll also need the corresponding CSS:

pre {
    background-color: #f1f1f3;
    border: 1px dashed #333333;
    padding: 10px;
    overflow: auto;
    margin: 4px 0px;
    width: 95%;
}

/* Syntax highlighting */
pre .normal {}
pre .comment { color: #999999; font-style: italic; }
pre .keyword { color: #006699; font-weight: bold; }
pre .method { color: #077; }
pre .class { color: #074; }
pre .module { color: #050; }
pre .punct { color: #000099; font-weight: bold; }
pre .symbol { color: #099; }
pre .string { color: #00CC00; }
pre .char { color: #00CC00; }
pre .ident { color: #333333; }
pre .constant { color: #0099CC; }
pre .regex { color: #00CC00; }
pre .number { color: #0099CC; }
pre .attribute { color: #5bb; }
pre .global { color: #7FB; }
pre .expr { color: #227; }
pre .escape { color: #277; }

I found this nifty information in an article called, "Howto format ruby code for blogs".