4

我有以下初始化程序:

app/config/initializers/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

我的 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

加上这个在 config/environments/development.rb

Foo::Application.configure do
# normal rails stuff
config.to_prepare do
    StoreLocation.skip_store_location
  end
end

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

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

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

4

1 回答 1

20

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

alias_method :devise_current_user, :current_user

以下

def current_user
  # do something
end

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

于 2012-08-07T15:05:56.560 回答