Rails Namespaced Helper

helper, ruby, ruby-on-rails

Solution

Helpers are mixed in the view, not in the controller. For example, if you have the following helper

module Authentication
  def current_user
    # ...
  end
end

and you include it in any controller

helper Authentication

calling `current_user` from an action will raise an undefined method error.

If you want to make some methods available to the view and the controller, you need a different approach. Define the methods and include the module as a normal module.

class MyController < ApplicationController
  include Authentication
end

and make the methods available as helpers.

class MyController < ApplicationController
  include Authentication

  helper_method :current_user
end

You can also take advantage of the `included` hook.

class MyController < ApplicationController
  include Authentication
end

module Authentication
  def self.included(base)
    base.include Helpers
    base.helper  Helpers
  end

  module Helpers
    def current_user
    end
  end
end

Problem

I have a controller `Api::V1::UsersController` in app/controllers/api/v1. I have a helper module `Api::V1::ErrorHelper` in app/helpers/api/v1. I want to access the helper modules's methods inside the controller. So, I called the controller's helper method, passing it the module: ``` class Api::V1::UsersController < ApplicationController helper Api::V1::ErrorHelper #other code end ``` But when I access one of the helper methods (respond_with_error) inside the controller I get following exception: ``` undefined method `respond_with_error' for #<Api::V1::UsersController:0x007fad1b189578> ``` How can I access this helper from the controller? (I am using Rails 3.2) Thanks.

Original source