BigBinary Blog

We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.

Rails 5 adds helpers method in controllers for ease

This blog is part of our Rails 5 series.

Before Rails 5, when we wanted to use any of the helper methods in controllers we used to do the following.

1
2module UsersHelper
3  def full_name(user)
4    user.first_name + user.last_name
5  end
6end
7
8class UsersController < ApplicationController
9  include UsersHelper
10
11  def update
12    @user = User.find params[:id]
13    if @user.update_attributes(user_params)
14      redirect_to user_path(@user), notice: "#{full_name(@user) is successfully updated}"
15    else
16      render :edit
17    end
18  end
19end
20

Though this works, it adds all public methods of the included helper module in the controller.

This can lead to some of the methods in the helper module conflict with the methods in controllers.

Also if our helper module has dependency on other helpers, then we need to include all of the dependencies in our controller, otherwise it won't work.

New way to call helper methods in Rails 5

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.

1
2module UsersHelper
3  def full_name(user)
4    user.first_name + user.last_name
5  end
6end
7
8class UsersController < ApplicationController
9
10  def update
11    @user = User.find params[:id]
12    if @user.update_attributes(user_params)
13      notice = "#{helpers.full_name(@user) is successfully updated}"
14      redirect_to user_path(@user), notice: notice
15    else
16      render :edit
17    end
18  end
19end
20

This removes some of the drawbacks of including helper modules and is much cleaner solution.

Abhishek Jain in Rails 5
June 26, 2016
Share

Subscribe to our newsletter