English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app

Simple String Concatenation of a Collection Written as a Helper for Rails


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 w/ #bookmarks #buffer #collection #content_tag #excerpt #helper methods #loop #rails #visual markupruby on rails