Method: AbstractController::Helpers::ClassMethods#helper_method

Defined in:
actionpack/lib/abstract_controller/helpers.rb

#helper_method(*meths) ⇒ Object

Declare a controller method as a helper. For example, the following makes the current_user controller method available to the view:

class ApplicationController < ActionController::Base
  helper_method :current_user, :logged_in?

  def current_user
    @current_user ||= User.find_by(id: session[:user])
  end

  def logged_in?
    current_user != nil
  end
end

In a view:

<% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>

Parameters

  • method[, method] - A name or names of a method on the controller to be made available on the view.



63
64
65
66
67
68
69
70
71
72
73
74
# File 'actionpack/lib/abstract_controller/helpers.rb', line 63

def helper_method(*meths)
  meths.flatten!
  self._helper_methods += meths

  meths.each do |meth|
    _helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1
      def #{meth}(*args, &blk)                               # def current_user(*args, &blk)
        controller.send(%(#{meth}), *args, &blk)             #   controller.send(:current_user, *args, &blk)
      end                                                    # end
    ruby_eval
  end
end