Rails Helper complete guide
Hi, This is Shubham Mishra from India, this is the part of Ruby on Rails exploration journey. In this post we will discuss about the Rails Helper method and its usage in the rails view and also its access in the terminal or controller. Even though we can access rails helper methods in the controller, but it is highly recommended not to use it, since it violets the rails architecture guideline. We will look how we can use existing rails helper methods, create custom rails helper and how to use it and also will look how to make use of rails helper defined outside the scope of ApplicationHelper. We will also explore some of the helpers provided by the Rails.
Now, lets understand each line in the above code
In rails there are some predefined helper methods are available, which you can directly use in the view. Let suppose we want to show user friendly time or days from a timestamp, then rails provide a helper method, time_ago_in_words. As, you can read in the code we can call that method in the view,
= time_ago_in_words(Time.now) #In the .haml file
<%= time_ago_in_words(Time.now) %> #In the .erb file
Sometimes we may want to check the helper methods in that case we can do so as mentioned in the code, through referring the helper class. In this case as the helper is belongs to application helper class hence we have called with ActionController::Base.helpers
In most of the time it happens that we have to define our own helper classes, then the approach is as simple as that,
- Identify the model for which you want to declare the helper method, for better structuring of the project, let suppose I want a helper for user's profile view where I want to show 'Jr.' or 'Sr.' on the basis of age of the person. So I will create a helper for User if not exist. Note it that you can write helper method in the ApplicationHelper for all your requirement but that will make your codebase unstructured, so I highly recommend to create respective helper class and to mess up the application helper class.
- Now see the code I have created user_helper.rb file, and created class UserHelper
- In the UserHelper, I have defined the required method, and then as shown in the last line you may use the helper method. Now, the same helper method can be reused at many places by just calling it and passing the age value as Integer.
= select_date(
Time
.today +
6
.days)
Now I think enough reading, I would suggest you to your rails and play with the code! 💻
Comments
Post a Comment