简体   繁体   中英

Ruby - Automatically running helper method

I have a login page saving a session to allow users to navigate subsequent pages. If you're not logged, I want to redirect you to the log in page. I have a SessionsHelper method for checking if the user is logged in and then if not, redirecting them back to the login page, But I don't want to have to call this in every controller action. Is there a way to easily run this method globally?

Traditionally this is done via a before_action filter. Something along these lines:

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

Also, helpers are for simplifying views (currency formatting, styling, etc.). They are not to be used for this kind of functionality (session management, in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM