Helpers in Ruby on Rails

toqeer__abbas

Toqeer Abbas

Posted on November 20, 2022

Helpers in Ruby on Rails

In this post i will discuss about helpers. I will cover all questions related to helpers in rails.

Why we need helpers?
A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods

How we can write helpers?

  • Create a new file under app/helpers.
  • Name it something like user_helper. rb.
  • Add a new module which matches the file name
`# app/helpers/user_helper.rb
module UserHelper
  def format_name(user)
    if user.gender == "M"
      "Mr. #{user.name}"
    else{% embed  %}
      "Ms. #{user.name}"
    end
  end
end`
Enter fullscreen mode Exit fullscreen mode

According to me helpers used in views. Never write your logics in views because that's like mess with views. your logics should be seprate from your views. For learn more watch this video

💖 💪 🙅 🚩
toqeer__abbas
Toqeer Abbas

Posted on November 20, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related