Take me home

Syntax highlighter

Published November 26, 2007

How I syntax highlight code in this blog. CodeRay + regular expressions.

I’m using this app-only plugin called cache_html. It lets me do this:

class Post < ActiveRecord::Base
  cache_html :intro, :content
end

This runs some parsing – textile and coderay – on that content, and stores it in [column_name]_html. Honestly, that’s kind of useless, as this app is using page caching, but oh well. Even the RSS feed is page cached, yawn.

So, the cache_html does it’s thing before_save, and this is one of the things:

def coderay(text)
  duped = text.dup
  expression = /(<source(?:\:([a-z]+))?>(.+?)<\/source>)/m
  text.scan(expression) do |all, language, code|
    language ||= :ruby

    if (code.scan(/\n/)).empty? # has no newlines?
      highlighted = '<span class="inline_code">'
      highlighted += CodeRay.scan(code, language.to_sym).div(:wrap => nil, :css => :class)
      highlighted += '</span>'
    else
      code.strip!
      highlighted = CodeRay.scan(code, language.to_sym).div(:css => :class)
    end

    duped.gsub!(all, "<notextile>#{highlighted}</notextile>")
  end

  duped
end

There ya go. Some notes:


Questions or comments?

Feel free to contact me on Twitter, @augustl, or e-mail me at august@augustl.com.