A view helper is a little piece of reusable code that you can place into your views to reduce the amount of code you have to repeat. You’ve probably already used some, such as form helpers (form_for) or others (image_tag). It’s also possible to make your own. If there’s something you do over, and over again, in multiple views, it’s worth considering making a helper to keep your code DRY and your typing fingers happy.
If you’ve never made a view helper before (or if you were shown how weeks ago, but forgot everything you learned, heh), it can seem a little intimidating. If you’re searching the internet for info, you’ll find lots of info related to older versions of rails, but little related to Rails 4.
Here are a few simple things to remember, and a nice resource that, combined, make it a piece of cake:
- The file must be placed in the app/helpers directory, and the file name must end with “_helper.rb”. I made one for centering images:
- The file name and module name must match in the same way controller names and class names match:
- If you’re including html code in your helper, it needs to be wrapped with the raw method:
raw('<a href="https://www.lianeallen.com/home/2014/09/view-helpers-for-noobs">Rails 4 View Helpers for Noobs</a>')
If you don’t wrap it in the raw method, rails is going to treat special characters as if they’re supposed to be text, and will escape them:
\<, \>, … etc.
so whatever you enter is going to be printed out as text in the view.
Unwrapped html as it will appear in your view:
<a href=”https://www.lianeallen.com/home/2014/09/view-helpers-for-noobs”>Rails 4 View Helpers for Noobs</a>
Wrapped html as it will appear in your view:
- And here’s a nice visual tutorial that will walk you through the simple process of creating and using your new helper: