Sam Soffes

Easy Syntax Highlighting

Posted on

Syntax highlight in Ruby is annoying. Pygments is the best way to do syntax highlighting, but it's a Python project. (Why no one has ported that to Ruby yet is beyond me. Granted there are a few, but they are all kinda annoying, slow, or don't work that well.)

Anyway, for awhile the best way was to hit a web service running on App Engine to use Pygments since that's actually running Python. This totally sucks because you have to rely on that service—it could be down, network latency, etc.

Damian Janowski put out a fantastic gem that solves this called Pygmentize. It's dead simple to use too.

require "pygmentize"
source = "function foo() { return 'bar'; }"
Pygmentize.process(source, :javascript)

The best part about all of this is that you can run it on Heroku! I switched my blog to use it and it's working great. By the way, if you're using Heroku, be sure you use the Cedar Stack.

Here's my little example page running on Heroku. The full source is on GitHub too. Enjoy!