vansan
vansan

Reputation: 762

uninitialized constant during rake assets:precompile for lib class

Rails 3.2.2

When running rake assets:precompile I get the following error:

uninitialized constant Redirect

Redirect is a custom middleware class that redirects naked domain requests from mydomain.com to www.mydomain.com.

I load the middleware in production.rb using:

config.middleware.use Redirect

The redirect.rb is located at lib/middleware/redirect.rb. I load the path in application.rb using:

config.autoload_paths += %W(#{config.root}/lib/middleware)

It works fine when you run the application, and other rake tasks run fine. But running rake assets:precompile appears to not load the lib properly. I first noticed the issue running on Heroku, but I've been able to reproduce locally no problem.

Any ideas? Thanks!

Upvotes: 3

Views: 1755

Answers (2)

Felix
Felix

Reputation: 694

I was getting the same error for loading a class from /lib and assigning it to a ::GLOBAL variable.

This was because I had forgotten to place it inside an after_initialize block, which is how I had done it in development.

config.after_initialize do
  ::GLOBAL = MyLib::MyClass.new
end

Hope this helps somebody!

Upvotes: 0

Jeremy Raines
Jeremy Raines

Reputation: 1739

You probably have config.assets.initialize_on_precompile = false set somewhere.

I experienced this error after setting that configuration for something related to Heroku. To fix, i just require "#{Rails.root}/lib/my_middleware.rb" right above the line where I configure the app to use the middleware.

Upvotes: 3

Related Questions