Adding markdown to your project

A quick one this time. I’ve just gone about implementing the following setup, which is a super easy way to add Markdown support in your views (and, well, anywhere).

We’ll be using the RDiscount gem for this. There are other gems like Bluecloth, but RDiscount has been consistently good for a long time now.

config/environment.rb add:

config.gem "rdiscount"

then install the new gem using “sudo rake:gems install” and restart rails…

…and that’s it. Now you can parse markdown into html like this:

RDiscount.new("My Lovely Markdown").to_html

But, that’s a mouthful and doesn’t look very clean in a view. So, what I did instead was to open up the String class and add a method called markdown which does that for us.

The easiest way to do that and make it available everywhere is to make an initializer.

Make the file “markdown.rb” in config/initializers/ and fill it with:

class String
  def markdown
    RDiscount.new(self).to_html
  end
end

After restarting rails, you will be able to convert markdown like this:

"My String".markdown

Now isn’t that special?

Sunday, September 27, 2009