7

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?

Community
  • 1
  • 1
George Armhold
  • 30,824
  • 50
  • 153
  • 232
  • 3
    Try to create a sub-directory under `classes` with the name of you module, then putting all the module's classes in there. I suspect if a file named `bar.rb` is changed, it is only reloaded if the class `Bar` is used, but not if the full name is actually `Foo::Bar` - then it would look for a file named `foo/bar.rb` to reload. Just a guess, though. – Thilo Jul 13 '12 at 14:18

1 Answers1

2

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • Module was declared in same file like: Module Foo; class Bar, and then referred to throughout the code as Foo::Bar. – George Armhold Jul 14 '12 at 15:02
  • It might be worth trying to have a separate module file just so there's a 1:1 association between classes/modules and files. – tadman Jul 15 '12 at 02:47