Rails View Helpers
Everyone can use a little help, sometimes...
2016-09-10
It isn’t always easy to know when to use Rails view helpers. You don’t want to sit down and try to write a bunch of helpers before you have a UI spec, or even before you’ve started to write a rough layout of your markup. But at some point, hopefully earlier in the implementation phase, it’s good to remember that helpers are there to help.
Consider the following markup for displaying a user’s profile image:
¶Traditional markup
|
|
This is functional code, but it has quite a bit of redundancy and, honestly, it’s not that easy to see what it’s doing at a glance. Now, let’s imagine what this part of our view would look like with a rails helper:
¶Rails Helper Version
|
|
Hopefully, the merit of simplicity is readily apparent. Replacing seven lines of html with a simple function call can be a big win, even if you’re only calling it once. If you end up using the same markup across many views in your app, the savings just multiply.
So, how should we think about view helpers? I like to follow a few basic principles that guide how I write markup.
¶Basic Principles
- Don’t Repeat Yourself
- Separate Semantics from Style
- Maintain Testability and Clarity of Intent
It would be cheating if I just showed you the code that used the helper without providing an example of the helpers implementation. Even though it’s quite powerful, it isn’t actually much more code:
¶Example Implementation
|
|
When you use a helper like this, you get clean, testable code that doesn’t need to be repeated every time you want to render a profile image in a view. And if you need to change how profile images are marked up later, only one simple method needs to be updated.
A Next Level Developer invests a little effort up-front so they can avoid complexity and save time later in the project.