Search code examples
ruby-on-railsrubymiddleware

What is wrong with how I'm attempting to load middleware?


I'm trying to write some middleware for a Ruby on Rails app. Here's what I have:

app/middleware/update_cache.rb:

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

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

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

Pretty straight-forward; nothing out of the ordinary. But when I make a request to the rails server, I get this error:

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

Out of curiosity, I thought I'd try to pass a class instead of a string to app.middleware.use, and got this backtrace:

/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>'

Is app/middlewhere/update_cache.rb the right place to put UpdateCache? What am I doing wrong?


Solution

  • There is probably another class in your app (or one of its dependencies) called UpdateCache and rails is picking up that one instead.

    To verify this you could remove this UpdateCache class and try evaluating UpdateCache from the rails console - if this doesn't raise an error then you'll have found your culprit.