December 7, 2006

Ruby Syntax Coloring For Your Blog Posts
Post by Peter Cooper

Ever wonder how people get syntax coloring like this?

class TrueClass; def =~(a); a[:ifTrue].call; end; end
class FalseClass; def =~(a); a[:ifFalse].call; end; end
def _(&a); lambda &a; end

(1 + 1 == 2) =~ { 
  :ifTrue => _{ puts "True" },
  :ifFalse => _{ puts "False" },
}

I know it doesn't look too hot on the green, but on white or grey it looks really good!

Want this sort of coloring on your blog? It's easy. Just paste your Ruby code in the box below, hit the button, then copy and paste the code from the box back into your blog / HTML page / etc.


You also need to have the following CSS styles at the ready:

pre {
        background-color: #f1f1f3;
        color: #112;
        padding: 10px;
        font-size: 13px;
        overflow: auto;
        margin: 4px 0px;
		width: 97%;
		overflow-x: auto;
		overflow-y: hidden;
		margin-top: 12px;
}


/* Syntax highlighting */
pre .normal {}
pre .comment { color: #005; font-style: italic; }
pre .keyword { color: #A00; font-weight: bold; }
pre .method { color: #077; }
pre .class { color: #074; }
pre .module { color: #050; }
pre .punct { color: #447; font-weight: bold; }
pre .symbol { color: #099; }
pre .string { color: #944; background: #FFE; }
pre .char { color: #F07; }
pre .ident { color: #004; }
pre .constant { color: #07F; }
pre .regex { color: #B66; background: #FEF; }
pre .number { color: #F99; }
pre .attribute { color: #5bb; }
pre .global { color: #7FB; }
pre .expr { color: #227; }
pre .escape { color: #277; }

Be sure to tweak it all to your own taste!

This all comes courtesy of the excellent Syntax gem by Jamis Buck. Check it out if you want to automate your own Web code coloring system.