Helpers in rails framework are live example of modules of ruby. The methods which are defined in helpers are available to the templates(view) by default. These helpers are called template helpers. Some examples are 1)date_helper.rb has methods like:
date_select,
datetime_select,
distance_of_time_in_words,
distance_of_time_in_words_to_now
2) form_helper.rb has methods like
fields_for,
file_field,
form_for
Now these helpers are there in the actionview gem which is installed along with rails gem.
In addition to using the standard template helpers provided to us by the rails framework ,we can also create custom helpers to extract complicated logic or reusable functionality which is strongly encouraged. By default, each controller will include all helpers. These helpers are only accessible on the controller through .helpers
In previous versions of Rails (rails 2, rails 3.0) the controller include a helper whose name matches that of the controller, e.g., HomeController automatically include HomeHelper. To return old behavior we can set config.action_controller.include_all_helpers to false. By default for Rails >= 3.1 all helper methods for one controller in the views can be used for a different controller.
We can define our custom helpers but to use them in controller we have to include them in controller.
module SiteHelper
def get_user_name(user)
name = user.first_name + user.last_name if user && user.first_name.present? && user.first_name.present?
end
end
Now to use this helper method we have to include this helper in controller using the helper class method:
class UsersController < ActionController::Base
helper SiteHelper
def index
@users = User.all
end
end
Then, in any view rendered by UsersController, the get_user_name method can be called:
<% @users.each do |user| -%>
<p>
<%= user.get_user_name %>
</p>
<% end %>
0 Comment(s)