Justin Marney

Pygrack, Pygments Highlighting Middleware

Rack, the ruby web server interface, has a powerful feature called rack middleware that allows you to filter requests and responses in your application. In an effort to explore the possible uses of middleware Lunar Logic Polska created CodeRack, a rack middleware coding contest. When Matt Swasey, a fellow Viget Labs developer, saw that Trevor Turk had created a pygments API he suggested that we create a CodeRack entry that uses the API to provide syntax highlighting to your rack application.


Pygments provides syntax highlighting via a Python library and command-line interface. Trevor Turk created a Google App Engine that provides an HTTP interface to the library. Basically, you send the engine some HTML via an HTTP request and it sends you the pygmentized version of the code you passed in. This allows systems and applications that don't have python available to use pygments. If you do have python installed you can add syntax highlighting to your ruby application via the albino library, a small wrapper around the pygments command-line interface.


Pygrack uses the built-in net-http library and nokogiri, an impressive markup parser, to inject pygment syntax highlighting into your rack application. In order to use Pygrack you'll need to add it to your rackup config.

require 'pygrack'

map "/" do
  use Pygrack
  run Rack::Directory.new("./public")

Next, wrap your code block in a pre tag with a class attribute that contains the language you want to apply to the block.

# make sure you dry all your glue

def sticking
 @gloo = 'pasting'
 puts @gloo
puts "glue is good for #{sticking}"

At this point you'll need to include one of the pygments css files. You can grab the default one from Trevor's pygments API repository or choose one from the list here. Start your rack application, using shotgun perhaps, and you should see some sweet pygments syntax highlighting. You can get the pygments code and see a simple rack application example at the pygrack github repository.