Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use domain objects from middleware with cache_classes off?

In the rails development environment, cache_classes is off so you can modify code under app/ and see changes without restarting the server.

In all environments, though, middleware is only created once. So if I have middleware like this:

class MyMiddleware

  def initialize(app)
    @app = app
  end

  def call(env)
    env['model'] = MyModel.first
  end

end

and I do this in config/environments/development.rb:

config.cache_classes = false # the default for development
config.middleware.use MyMiddleware

then I'll always get the following error:

A copy of MyMiddleware has been removed from the module tree but is still active!
  /Library/Ruby/Gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:414:in `load_missing_constant'
  /Library/Ruby/Gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:96:in `const_missing'
  /Users/me/projects/my_project/lib/my_middleware.rb:8:in `call'
  /Library/Ruby/Gems/1.8/gems/actionpack-2.3.2/lib/action_controller/middleware_stack.rb:72:in `new'
  ...

The problem is that the MyMiddleware instance is created once at system load time, but the MyModel class is reloaded on each call.

I tried 'MyModel'.constantize.first to delay binding to the class until method-call-time, but that changes the problem to a new one:

You have a nil object when you didn't expect it!
The error occurred while evaluating nil.include?
  /Library/Ruby/Gems/1.8/gems/activerecord-2.3.2/active_record/attribute_methods.rb:142in `create_time_zone_conversion_attribute?'
  /Library/Ruby/Gems/1.8/gems/activerecord-2.3.2/active_record/attribute_methods.rb:75:in `define_attributes_methods'
  ...
like image 673
James A. Rosen Avatar asked Jun 13 '09 17:06

James A. Rosen


1 Answers

This appears to be a Rails bug. See if you can upgrade your Rails version to 2.3.4 or 2.3.5.

I believe this is the commit that fixed the problem. Original bug report is here.

like image 154
molf Avatar answered Nov 02 '22 20:11

molf