Using Rails Helpers inside a Controller

Rails helpers are designed to be used inside views, but sometimes you might want the functionality from a helper inside your controller. For example, you might be generating a simple JSON string and you want to use a view helper to format some element of the JSON.

One way of doing this would be to include the helper directly into the controller (by simply doing include HelperName). I’m not a big fan of this approach since this includes all the helper’s methods in all your controller actions.

Another approach (which I prefer) is to declare the helper method as a class function and then simply reference the helper directly in your controller.

class MyController < ApplicationController
  def action
    @url = UrlHelper.generate_url(current_user)
  end
end

Of course, helper methods are not declared as class methods which means this code sample will fail. A relatively clean way to get around this is to simply declare a class method and have the regular helper method reference the class method.

module UrlHelper
  def self.generate_url(user)
    "http://www.google.com/#q=#{user.name}"
  end
  
  def generate_url(user)
    UrlHelper.generate_url(user)
  end
end

Now your helper’s functionality is still available in your views, but you can also use specific methods in other parts of your application as necessary. Happy coding.