Notebook

July 15, 2008 1:46AM

Pass Blocks to Your Markdown Helper

For the new site, I'm going to be using Markdown to handle the formatting of all of my content. I created a simple helper to make things easy:

def markdown(str)
  RDiscount.new(str).to_html
end

(Note: I'm using the RDiscount library instead of BlueCloth, for reasons discussed here)

However, what if I wanted to add a "Read more" link at the end of the entry excerpt? I'd have to do something like this:

<%= markdown entry.excerpt + link_to("Read more", entry_path(entry)) %>

This way didn't really appeal to me. What I really wanted to do was just pass a Ruby block, like this:

<% markdown do %>
  <%= entry.excerpt %> <%= link_to "Read more", entry_path(entry) %>
<% end %>

In order to do this, I just had to modify my markdown helper a bit:

def markdown(str='', &block)
  str    = capture(&block) if block_given?
  result = RDiscount.new(str).to_html

  block_given? ? concat(result, block.binding) : result
end

And, just like that, I can now pass blocks to my Markdown helper.

Did you like this entry? Make sure to subscribe to my RSS feed to keep up-to-date with my newest entries and links.

Comments

Leave a Comment

(required)

(required, never displayed)

(optional)

Ajax-loader

About

This entry was published on July 15, 2008. 0 responses have been posted.

Tags: , ,

Links

Important links from within the post.