我如何尝试加载中间件有什么问题?

时间:2015-12-17 00:35:55

标签: ruby-on-rails ruby middleware

我正在尝试为Ruby on Rails应用编写一些中间件。这就是我所拥有的:

应用/中间件/ update_cache.rb:

class UpdateCache
  def initialize(app)
    @app = app
  end

  def call(env)
    @app.call(env)
  end
end

配置/ application.rb中:

require File.expand_path("../boot", __FILE__)
require "rails/all"
Bundler.require(*Rails.groups)

module MyApp
  class Application < Rails::Application
    config.middleware.use("UpdateCache")
  end
end

相当直接;没什么特别的。但是当我向rails服务器发出请求时,我收到了这个错误:

undefined method `call' for #<UpdateCache:0x00000003eec1b0>

出于好奇,我以为我试图将一个类而不是一个字符串传递给app.middleware.use,并得到了这个回溯:

/home/fred/my_app/config/application.rb:7:in `<class:Application>': uninitialized constant MyApp::Application::UpdateCache (NameError)
    from /home/fred/my_app/config/application.rb:11:in `<module:MyApp>'
    from /home/fred/my_app/config/application.rb:10:in `<top (required)>'
    from /home/fred/.gem/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:78:in `require'
    from /home/fred/.gem/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:78:in `block in server'
    from /home/fred/.gem/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:75:in `tap'
    from /home/fred/.gem/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:75:in `server'
    from /home/fred/.gem/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /home/fred/.gem/gems/railties-4.2.4/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:8:in `require'
    from bin/rails:8:in `<main>'

app / middlewhere / update_cache.rb是放置UpdateCache的正确位置吗?我做错了什么?

1 个答案:

答案 0 :(得分:2)

您的应用程序(或其中一个依赖项)中可能还有另一个名为UpdateCache的类,而rails正在拾取该类。

要验证这一点,您可以删除此UpdateCache类并尝试从rails控制台评估UpdateCache - 如果这不会引发错误,那么您将找到您的罪魁祸首。