0

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?

Synthead
  • 2,162
  • 5
  • 22
  • 25
  • 1
    your problem have the answer. http://stackoverflow.com/questions/3428343/where-do-you-put-your-rack-middleware-files-and-requires – Auli Dec 17 '15 at 03:26
  • 1
    To me this sounds like there is another class called UpdateCache that is shadowing yours (could be from your app, another gem etc.) – Frederick Cheung Dec 17 '15 at 09:45
  • @user3762171: I saw that post, but to the best of my understanding, I'm following their suggestions verbatim. What do you suggest? – Synthead Dec 17 '15 at 18:22
  • @FrederickCheung: Holy crap, that was it! Wow, I could have been stuck on that for a while. Submit a response and I'll mark it as the correct answer! – Synthead Dec 17 '15 at 18:28

1 Answers1

2

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.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174