Written by Sean Behan on Sun Jun 17th 2012

At Railsconf last week I took Greg Pollack's online course Rails Best Practices. The interface is gorgeous and the instructions are excellent. One of the lessons involved taking a partial and moving it into a helper. I was reminded how difficult such a simple task can be. I have written about this before Yield a Block Within Rails Helper Method with Multiple Content Tags. However, that post aims to solve a slightly different problem, where the helper method takes the captured text from a block passed as an argument which essentially acts as a wrapper.

The difficulty isn't with the logic itself and or the complexity/verbosity that the code is likely to produce. Rather, it is difficult because you have to endlessly concatenate strings and this something somewhat uncommon when programming with ruby. We have to remember that we're working with a buffer of text about to be flushed. Here is a simple code snippet that shows how to write a helper method that loops over a collection of objects.

  def bookmarks_for(user=nil)
    content_tag(:div, :id => "bookmarks") do
      user.bookmarks.each do |bookmark|
          content_tag(:strong) { bookmark.member_name } +
          excerpt(bookmark.body, '', 100)

Notice the use of the concat() method the "+" sugb and .join() method. All three of which bring these statements together into one final piece of html called in the view.

<%= bookmarks_for(@user) %>

Tagged with..
#bookmarks #buffer #collection #content_tag #excerpt #helper methods #loop #Rails #visual markup #Ruby on Rails

Just finishing up brewing up some fresh ground comments...