Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.2.x: how to reload app/classes dir during development?

I have some Rails code that does not fit neatly into a model or controller box. So as per this answer, I created a app/classes directory. Rails 3 seems to automatically add this to the "load path" in Rails, and my application correctly finds the classes I define in there without needing to use require statements.

However the code in app/classes does not get reloaded in development mode; if I make a change, I need to restart the server in order to see that change.

What's the proper way to make a given directory "reloadable" in Rails 3.2.x? A few answers here recommend doing:

config.autoload_paths += %W(#{config.root}/app/classes)

but I believe that this merely has the effect of adding app/classes to the initial set of directories to find code in; does not seem to make them reloadable for each request (and furthermore in 3.x it seems that app/* is automatically added).

Update:

Figures, I stumbled upon the solution a mere 30 seconds after posting the question:

I had my class wrapped inside a module. Once I removed the surrounding "MyModule", it suddenly became reloadable. Coming from a Java background, and having been burnt by Ruby code that pollutes the global namespace, I've developed a habit of putting everything inside a module. I guess Rails "app" code must live outside of any module?

like image 866
George Armhold Avatar asked Jul 13 '12 13:07

George Armhold


1 Answers

Did you declare the module in a separate file, or did you declare it implicitly inside the class? This might have an effect on autoload behavior. module Foo; class Bar vs. class Foo::Bar. It might be if the Rails autoloader can't find a foo.rb to go with the Foo module it might skip reloading it.

like image 100
tadman Avatar answered Nov 15 '22 09:11

tadman