Restricted if and loops inside the views? (BAD PRACTICES)

Need an expert or real rails documentation. I’m a beginner on ruby on rails and this is my third project where I decide to use for and some if statements to display information (we are using devise gem)

----index.html.erb----- <% if user_signed_in? %> Text1 <% else > Text2 <% end>

I got the next review from another student: “View-related logic can be encapsulated in View helpers (app/helpers/*_helper.rb) There should be absolutely NO logic in views(ifs, loops…).” Hi’s justifying his review whit the next unreliable post whit no enough information: Where Do I Put My Code?

However, we tried looking for documentation about this and were not able to find something that fully justifies this change. We believe that it doesn’t represent proper optimization and it will make the loading time heavier because additional functions just to get a STRING. We also looked at the blog and it doesn’t fully explain the logic behind making this change. Could you please help by us issuing official documentation about rails that can explain this requirement in detail?

Welcome to the discussion! I’d be happy to help you. This is good feedback, and it makes a lot of sense to keep the ERB templates as “dumb” as possible. Helpers are one place you can put things like this. As you move into more complex calculations, you may want to graduate up to decorators, perhaps using the Draper gem. Helpers inherit the same namespace as the view templates, so anything you have available at the ERB level will be available in helpers, too.

One thing to understand, even though helpers are usually named for their model, this is mostly a convenience for you when you start looking for where you hid that code. In the default setup, Rails coalesces all the helpers together into one namespace, so you need to name your methods in a globally-unique manner.

Something like this might help:

# user_helper.rb
module UserHelper
  def user_intro_text
    return 'Text1' if user_signed_in?
    'Text 2'
  end
end

Walter

I prefer using github/view_component. Do not like Rails helpers too much for the reason that they are pollute codebase.