Howto format ruby code for blogs
Posted by Jim Morris on Fri May 26 00:14:00 -0700 2006
How do I get that nice formatted ruby code inline?
Well if you are on typo trunk use this...
<typo:code lang="ruby">
...ruby code...
</typo:code>
If you are not on typo trunk (which I am not yet) you can do the following...
I had to search around for this so I thought I'd put the recipe here.
I got most of my information from this site, you can also use this site to convert the code for you, but I found that more cumbersome than what I do below.
Basically all the hard work is done by the syntax gem install it as...
Then I use this little script called code2html.rb which converts the code in the clipboard and puts it back in the clipbboard...
require 'rio' require 'rubygems' require 'syntax/convertors/html' if ARGV.size > 0 code= File.read(ARGV[0]) else code= `dcop klipper klipper getClipboardContents` end convertor = Syntax::Convertors::HTML.for_syntax "ruby" @code_html = convertor.convert( code ) puts @code_html if ARGV.size > 0 fn= "#{File.basename(ARGV[0], File.extname(ARGV[0]))}.html" rio(fn) << @code_html else # put the results back on the clipboard, NB this may fail if there are shell specific characters system("dcop klipper klipper setClipboardContents \"#{@code_html}\"") end
The clipboard stuff is kind of kde specific.
Alternatively you can specify a filename on the command line, and it will convert that file and put the results in a file with .html as the extension. (Note this requires the rio gem).
You will need this CSS available to your web page to render it nicely.
pre {
background-color: #f1f1f3;
color: #112;
padding: 10px;
font-size: 1.1em;
overflow: auto;
margin: 4px 0px;
width: 95%;
}
/* 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; }
Show