on
Syntax Highlighting for Ruby
There are more than couple of ways to do syntax highlighting for Ruby code. Your geek blog doesn’t look nice if the code cannot be read properly or cannot be copied easily. Gists work well. Most blogs now would probably just use gist.github.com especially if it’s lengthly file or there are way to many stuff on it that you don’t want to scare your visitors. By naming the file “syntax.rb” on gist.github.com for instance, it would know what code you are using and syntax highlighting will be based on the filename. See syntax.rb .
The following code used to work well for me:
def to_html(markdown)
out = []
noncode = []
code_block = nil
markdown.split("\n").each do |line|
if !code_block and line.strip.downcase == '```ruby'
out << Maruku.new(noncode.join("\n")).to_html
noncode = []
code_block = []
elsif code_block and line.strip.downcase == '```'
convertor = Syntax::Convertors::HTML.for_syntax "ruby"
highlighted = convertor.convert(code_block.join("\n"))
out << "```ruby#{highlighted}```"
code_block = nil
elsif code_block
code_block << line
else
noncode << line
end
end
out << Maruku.new(noncode.join("\n")).to_html
out.join("\n")
end
There are at least two problems with this code:
- Maruku, a markdown interpreter is slow. At least slower than RDiscount, another Markdown interpreter.
- The output doesn’t look good even with CSS work done. There’s white-space before the code making it appear intended when it fact it is not.
- There are just too many lines of code. Period.
I had to convert everything to HAML recently. Starting to feel an aversion towards using and overusing ERB.
This code works for me:
def to_html(markdown)
markdown = markdown.gsub("```ruby", '```ruby').gsub("```", "``` ")
markdown = RDiscount.new(markdown)
markdown = markdown.to_html
end
Why the code above is better:
- Uses RDiscount gem which is faster than Maruku
- It is intended to work with Javascript Syntax Highlighter. Just make sure to include the brush for Ruby on head tag along with the core.
- It allows user to copy and print the code
- It’s shorter