Last Updated: February 25, 2016
·
584
· yannis

Ruby on Rails: Declare a controller method as a helper

From Rails doc (http://api.rubyonrails.org/classes/AbstractController/Helpers/ClassMethods.html).

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 -%>