Using Rails helpers to hide the cruft

Using helpers to hide the cruftViews are the messiest part of an application. Nested divs, content inside layouts inside boxes inside partials, and a dash of javascript with it’s own ugly syntax. Last week I presented a good way to clean up views using partials with layouts. But the “proper” way to cleanup views is using helpers.

Rails helpers are what you use when you need to cleanup lots of repeating but still very small strings of text. An awesome use are menus. I typically use a helper for all inline menus since they are repetitious and consist of text inside links inside list items inside unordered lists.

Today I found out that a great way to use a helper is for the Live Validation javascript constructor.

The Live Validation constructor I want to use is kind of large and crufty; it looks out of place in my clean Ruby-esque view templates. So I got rid of all repetition using a neat little helper. This time it’s just a simple string replacement:

  # Render a Live Validation constructor in javascript.
 
  def live_validation(element)
 
    "var #{element} = new LiveValidation('#{element}', {onValid: function() {
 
      this.removeMessage(); this.removeFieldClass();
 
    }, onlyOnBlur: true});"
 
  end

Even though it’s just an insignificant text helper, using <%=live_validation ‘user_email’%> looks a lot better than the entire thing above inside my views! Especially when there’s four or five fields to validate.

As a side note, feel free to use the constructor above if you want to use Live Validation without an ‘okay’ message. This is the proper way to do that.

0 Responses to “Using Rails helpers to hide the cruft”


  1. No Comments

Leave a Reply




About Bemba Media

Bemba Media is a new social media company based in Amsterdam, the Netherlands. Founders Aaron Peters and Arne Dibbits are on a mission to offer people the easiest way to share their web experiences with friends and to discover what’s hot on the web right now.

The company launched Bemba.com in March 2008.

Bemba users share their favorite videos and websites on the social platforms they already use with their friends, like Facebook, Twitter and Hyves. More social networks and (micro-) blogs will follow.

Bemba will become a destination for 'funsurfing' the web, providing easy access to web content that people with similar interests have recently recommended to their friends.

Flickr photos

meeting with Sanoma NL in Hoofddorp #

Bemba blog in Wordle

More Photos

Twitter updates

    Recent readers