初始化程序更改'alias_method'未定义方法'current_user'用于类'ApplicationController'

win*_*ons 4 devise ruby-on-rails-3

我有以下初始化程序:

应用程序/配置/初始化/ store_location.rb

module StoreLocation

  def self.skip_store_location
    [
        Devise::SessionsController,
        Devise::RegistrationsController,
        Devise::PasswordsController
    ].each do |controller|
      controller.skip_before_filter :store_location
    end
  end

  self.skip_store_location
end
Run Code Online (Sandbox Code Playgroud)

我的ApplicationController的相关部分:

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :convert_legacy_cookies
  before_filter :store_location

  alias_method :devise_current_user, :current_user

  def current_user
    # do something
  end

  private
  def store_location
    # store location
  end
Run Code Online (Sandbox Code Playgroud)

另外在 config/environments/development.rb中

Foo::Application.configure do
# normal rails stuff
config.to_prepare do
    StoreLocation.skip_store_location
  end
end
Run Code Online (Sandbox Code Playgroud)

如果我让RSpec/Rails运行self.skip_store_location,我收到以下错误:

/foo/app/controllers/application_controller.rb:7:in `alias_method': undefined method `current_user' for class `ApplicationController' (NameError)
Run Code Online (Sandbox Code Playgroud)

如果我删除了呼叫,一切都恢复正常(除了按预期运行过滤器).我猜我以某种方式搞乱了依赖加载?

Tam*_*ese 18

问题是您alias_method在定义方法之前使用ApplicationController.要解决此问题,请移动该行

alias_method :devise_current_user, :current_user
Run Code Online (Sandbox Code Playgroud)

下面

def current_user
  # do something
end
Run Code Online (Sandbox Code Playgroud)

运行时出现错误有点误导skip_store_location.我认为这是因为skip_store_location加载了几个控制器,其中一个是子类ApplicationController.

  • 我尝试了你的方法,但 StackLevel 出现了严重错误,现在我在“current_user”方法中使用“super”调用,它可以工作。重要的是要找出罪魁祸首。非常感谢你是个天才! (2认同)