I saw this article on formatting ruby code for blogs. Nice article, but the code is Linux/KDE-specific. Also, OS X threw an error about the order of the require statements. Being that I use OS X (and so should you) I needed to make a couple of changes to the code that supports the clipboard (via the Linux/KDE dcop command). Enter pbcopy and pbpaste.

You can find out more about pbcopy and pbpaste by either looking at the documentation in the OS X terminal using the man command or by going to this Mac OS X Tips & Tricks page. In short, using pbcopy and pbpaste you can move data from the OS X terminal (or via ruby or other scripting languages) in and out of the clipboard.

With a couple of changes to the code we’re in business in OS X

	
	#!/usr/bin/env ruby
	#
	#  Created by David Orriss Jr on 2007-09-23.
	#  Copyright (c) 2007. All rights reserved.
	#  Based on "Howto format ruby code for blogs" at
	#  http://blog.wolfman.com/articles/2006/05/26/howto-format-ruby-code-for-blogs

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

	if ARGV.size > 0
	    code= File.read(ARGV[0])
	else
	    code= 
	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("echo "#{@code_html}" | pbcopy")
	end
	

Don’t forget to add this to your stylesheet in your blog otherwise everything in the above code will be preformatted but without any color highlighting:

	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; }