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.

module UsersHelper
  def full_name(user)
    user.first_name + user.last_name
  end
end

class UsersController < ApplicationController
  include UsersHelper

  def update
    @user = User.find params[:id]
    if @user.update_attributes(user_params)
      redirect_to user_path(@user), notice: "#{full_name(@user) is successfully updated}"
    else
      render :edit
    end
  end
end

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.

module UsersHelper
  def full_name(user)
    user.first_name + user.last_name
  end
end

class UsersController < ApplicationController

  def update
    @user = User.find params[:id]
    if @user.update_attributes(user_params)
      notice = "#{helpers.full_name(@user) is successfully updated}"
      redirect_to user_path(@user), notice: notice
    else
      render :edit
    end
  end
end

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