Views 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.

Subscribe to our RSS feed


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