A
A
Arsenikum2016-02-27 23:58:17
Ruby on Rails
Arsenikum, 2016-02-27 23:58:17

Why are helpers needed in the context of controllers/views?

What is a helper in a Ruby on Rails application? Why are helpers needed in the context of controllers/views?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vsuhachev, 2016-02-28
@Arsenikum

It is considered bad form to add too much code to a view. If this code is logically related to the controller or model, then there is no problem - place it there. But sometimes there is code purely for presentation. For example, you need to display a list of tags with localization.
Of course, you can place such code in a view

<%- product.tags.each do |tag| %>
  <p>
    <%= I18n.t(tag, scope: "very.very.very.very.very.very.very.very.long.string.#{product.category}", default: tag.to_s.humanize) %>
  </p>
<%- end %>

And you can remove it in the helper
def localized_tags(product)
  product.tags.map do |tag|
    I18n.t(tag, scope: "very.very.very.very.very.very.very.very.long.string.#{product.category}", default: tag.to_s.humanize)
  end
end

And then you get the first benefit: readable view code
<%- localized_tags(product).each do |tag| %>
  <p><%= tag %></p>
<%- end %>

And the second advantage: you can reuse localized_tags, write tests on it, etc. And your models and controllers are not littered with view logic.

A
Alexander Wolf, 2016-02-28
@mannaro

I won’t say exactly why they are needed in controllers, but in views they are needed in order to predefine some function in order to use it in the view.
I think in the controller as well, but for me it's more convenient to just define a new method and use it as a helper.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question