Ruby - Automatically Managed Helper Method

I have a login page that saves the session so that users can navigate through subsequent pages. If you are not logged in, I want to redirect you to the login page. I have a SessionsHelper method for checking a user’s login, and then, if not, redirecting back to the login page, but I don’t want this to trigger this with every controller action. Is there a way to easily run this method around the world?

+4
source share
1 answer

Traditionally, this is done using the before_action filter. Something like that:

 class ApplicationController before_action :require_current_user def require_current_user redirect_to login_path unless current_user end end class SessionsController < ApplicationController # do not cause endless redirect loop skip_before_action :require_current_user, only: [:new, :create] end 

In addition, helpers are designed to simplify browsing (currency formatting, styling, etc.). They are not used for this kind of function (session management in this case).

+5
source

All Articles