Saturday, January 22, 2011

Dear Lazyweb: How can I put many classes in one file in a Rails app?

Since yesterday, I asked many of my Rails friends the same question:

How can I put many classes in one file in a Rails app?

Unfortunately, I haven't got any answer that would work.

I try to solve this problem every 6 months or so. It's not a thing that I can't live without, but it would help my workflow a lot.

One use case is to put 4-5 model classes in one file. If each class is only 15 lines and they're all conceptually related then why not to put them together?

Another use case is to keep related controllers in one file.

So far I tried a combination of require, require_dependency and autoload and I tried to put them in config/initializers, environment.rb or in application_controller. Each resulted in some kind of error. Either  one of the class was not found, or Rails complained with "A copy of ApplicationController has been removed from the module tree but is still active!".

I tried all of it with Rails 2.3.5 in development mode, however a solution that works with Rails 3 would also be great!

Can anyone help?

4 comments:

Anonymous said...

You say you tried in development mode, thus cache_classes = false. Have you tried with true, and requiring your files manually?

I suspect this will never work when cache_classes = false, since Rails' magic expects to find files named after the class.

Andrzej Krzywda said...

I'd love to have the ability to cache classes in development mode, so that there's no need to restart the server after the files change.

Actually, I could live with that, but I'm not the only developer in this project.


"I suspect this will never work when cache_classes = false, since Rails' magic expects to find files named after the class."

I still hope that I can work around this "magic" somehow.

Krzysztof Cierpisz (chris) said...

It looks like you want to break Rails' convention of "one class per file".

Andrzej Krzywda said...

"It looks like you want to break Rails' convention of "one class per file"."

Yes, I'd prefer to have it possible.

I don't think that this "feature" was ever advertised as a good thing. Was it? I don't see any value in it.

Automatic class reloading in development mode could be implemented even when you have multiple classes per file.