我想覆盖devise gem的authenticate_user和current_user方法

我想覆盖authenticate_user! 和我的应用程序控制器中的devise gem的current_user方法可以请你帮我解决这个问题

您可以像以下一样进行猴子修补:

module Devise module Controllers module Helpers def authenticate_user! #do some stuff end end end end 

但我会问最终的目标是什么,因为Devise已经内置了一些可定制性,并且覆盖这些方法让我想知道“为什么要使用Devise?”

覆盖用户的身份validation方式:

Devise在引擎盖下使用Warden https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb

因此,您只需在Warden中添加新策略即可对用户进行身份validation。 请参阅https://github.com/hassox/warden/wiki/Strategies

您不应该覆盖current_user。 你面临什么挑战? 你需要退回不同的型号吗?

您必须创建一个自定义类来覆盖默认的Devise行为:

  class CustomFailure < Devise::FailureApp def redirect_url #return super unless [:worker, :employer, :user].include?(scope) #make it specific to a scope new_user_session_url(:subdomain => 'secure') end # You need to override respond to eliminate recall def respond if http_auth? http_auth else redirect end end end 

在你的config / initializers / devise.rb中:

  config.warden do |manager| manager.failure_app = CustomFailure end 

但我建议查看Devise文档:)

https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated

如果要将代码添加authenticate_user!

 class DuckController < ApplicationController before_action :authenticate_duck ... private def authenticate_duck #use Devise's method authenticate_user! #add your own stuff unless current_user.duck.approved? flash[:alert] = "Your duck is still pending. Please contact support for support." redirect_to :back end end end 

application_controller.rb您可以根据需要覆盖:

 def authenticate_user! super # just if want the default behavior call_a_method_to_something if current_user # or call_a_method_to_something if current_user.nil? end