Lesson Monday

In a previous lesson, we used a conditional to protect content in our views. While this piece of code works, it will get repetitive very quickly, especially if we have lots of content to protect. Let's use a helper method to dry up our code.

Helper Methods


A helper method is a small utility function that can be used to extract logic from views and controllers, keeping them lean. Views should never have logic because they're meant to display HTML. In addition, there's no way to test view logic, but if we extract this logic into methods it can then be tested.

We'll start by putting a helper method in our application controller.

application_controller.rb
class ApplicationController < ActionController::Base
  helper_method :is_admin?

  def is_admin?
    current_user && current_user.admin
  end

end

By putting this helper method in the application controller, we make it available to all of our controllers and views. First we declare that the is_admin? method is a helper method. Then we define it. Now we can say <% if is_admin? %> method in our views instead of using <% if current_user && current_user.admin %>.

Helper Method Placement

Great, right? Not so fast. While we do want to make helper methods available to both our controllers and views sometimes, let's imagine we only need this method for our views because we already have other logic to handle authentication in our controllers. This means our helper method doesn't belong in our application controller. Good code separates concerns as much as possible and scopes methods so they're only available where they need to be used.

So where does our helper method go?

If you go to app > helpers, you'll see a file called application_helper.rb. Let's put the code there instead:

application_helper.rb
module ApplicationHelper
  def is_admin?
    current_user && current_user.admin
  end
end

All helper methods in the helpers folder will only be available to the views. Now we have a helper method that is available only where we need it.

Other Options

Okay, great! We finally have a good, clean piece of code. Right?

Well, not necessarily. Many good developers believe there are inherent problems with Rails helper methods because of the way they are namespaced and made available globally. For these developers, using decorators with a tool like the Draper gem is a better option.

We encourage you to explore helper methods in your own applications. You aren't required to test your helper methods but are encouraged to do so. If you'd like to explore further, you can try out the Draper gem. Even if helper methods can potentially cause issues, the benefits of DRYing up code and communicating intentions via helper methods is a huge positive.

Sample helper method

application_helper.rb
module ApplicationHelper
  def is_admin?
    current_user && current_user.admin
  end
end

Lesson 13 of 27
Last updated July 14, 2022