What do helper and helper_method do?

Viewed 103905

helper_method is straightforward: it makes some or all of the controller's methods available to the view.

What is helper? Is it the other way around, i.e., it imports helper methods into a file or a module? (Maybe the name helper and helper_method are alike. They may rather instead be share_methods_with_view and import_methods_from_view)

reference

2 Answers

A Helper method is used to perform a particular repetitive task common across multiple classes. This keeps us from repeating the same piece of code in different classes again and again.

Here's an example to simplify the above definition:

Here is a code, where you would have something like this in the view:

<% if @user && @user.email.present? %>
  <%= @user.email %>
<% end %>

We can clean it up a little bit and put it into a helper:

module SiteHelper
  def user_email(user)
    user.email if user && user.email.present?
  end
end

And then in the view code, you call the helper method and pass it to the user as an argument.

<%= user_email(@user) %>

This extraction makes the view code easier to read especially if you choose your helper method names wisely.

So I hope this clears things up a little for you.

Source for the quotation Source for the code

Related