【发布时间】:2011-09-19 11:51:26
【问题描述】:
我想覆盖 authenticate_user!和我的应用程序控制器中设计 gem 的 current_user 方法你能帮我解决这个问题吗 谢谢
【问题讨论】:
标签: ruby ruby-on-rails-3 rubygems
我想覆盖 authenticate_user!和我的应用程序控制器中设计 gem 的 current_user 方法你能帮我解决这个问题吗 谢谢
【问题讨论】:
标签: ruby ruby-on-rails-3 rubygems
你可以像猴子一样修补它:
module Devise
module Controllers
module Helpers
def authenticate_user!
#do some stuff
end
end
end
end
但我会问最终目标是什么,因为 Devise 已经内置了一些可定制性,而重写这些方法让我想知道“为什么要使用 Devise?”
【讨论】:
application_controller.rb 中编写自定义方法是一样的吗?谢谢!
application_helper.rb 中,因为它覆盖了一个辅助方法。但你也可以把它放在你提到的地方。
关于覆盖用户的身份验证方式:
Devise 在后台使用 Warden https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb
因此,您可以在 Warden 中添加一个新策略来验证您的用户。看 https://github.com/hassox/warden/wiki/Strategies
您不需要覆盖 current_user。你面临什么挑战? 您需要返回不同的模型吗?
【讨论】:
您必须创建一个自定义类来覆盖默认的设计行为:
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 文档 :)
【讨论】:
如果你想添加代码到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
【讨论】: