Screen capture from http://www.rails-dev.com/custom-view-helpers-in-rails-4

Rails 4 View Helpers for Noobs

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:

  1. 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:

    app/helpers/centering_helper.rb

  2. The file name and module name must match in the same way controller names and class names match:

    centering_helper.rb
    module CenteringHelper

  3. If you’re including html code in your helper, it needs to be wrapped with the raw method:

    raw('<a href="http://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=”http://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:

    Rails 4 View Helpers for Noobs

  4. And here’s a nice visual tutorial that will walk you through the simple process of creating and using your new helper:
    http://www.rails-dev.com/custom-view-helpers-in-rails-4

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.