Ruby on rails Rails include模块根据模块包含的位置引发异常
我试图从主控制器中提取错误处理,因此创建了一个模块:Ruby on rails Rails include模块根据模块包含的位置引发异常,ruby-on-rails,ruby,Ruby On Rails,Ruby,我试图从主控制器中提取错误处理,因此创建了一个模块: module Error module ErrorHandler def self.included(klass) klass.class_eval do rescue_from StandardError do |e| respond(:standard_error, 500, e.to_s) end end end def respond
module Error
module ErrorHandler
def self.included(klass)
klass.class_eval do
rescue_from StandardError do |e|
respond(:standard_error, 500, e.to_s)
end
end
end
def respond
#...
end
end
end
在我的应用程序
控制器中,我有:
class ApplicationController < ActionController::API
include ActionController::Cookies
include Error::ErrorHandler
before_action :authenticate_request
attr_reader :current_user
private
def authenticate_request
@current_user = AuthorizeApiRequest.call(cookies[:auth]).result
render json: { authorized: false }, status: 401 unless @current_user
end
def serialize(data, **options)
Serializer.serialize(data, options)
end
end
class ApplicationController
现在,如果我将Error::ErrorHandler包含在其中,我将得到一个名称错误或方法错误:
NameError (undefined local variable or method `current_user' for #<Users::PerformancesController:0x00007f8f75fda5f0>):
NoMethodError (undefined method `authenticate_request' for #<Users::PerformancesController:0x00007f8f76f40378>):
NameError(未定义的局部变量或#的“当前用户”方法):
NoMethodError(针对#的未定义方法“authenticate_request”):
但是,如果我将include移到ApplicationController的底部,一切都会正常工作
知道为什么会发生这种情况吗?旁注:
ErrorHandler
甚至不会通过Ruby解析器(打开的块没有关闭end
)很好。修复了它。感觉ApplicationController中的代码没有在包含ErrorHandler
的行之后运行。你能检查一下执行是否完成了吗?@Darkisa你解决了这个问题吗?旁注:ErrorHandler
甚至不会通过Ruby解析器(打开的块没有关闭end
)很好。修复了它。感觉ApplicationController中的代码没有在包含ErrorHandler
的行之后运行。你能检查一下死刑是否已经执行了吗?@Darkisa你把这个修好了吗?