views:

490

answers:

5

I have numerous models in my app/models folder. I'd like to clean this folder up a little bit. Move models that belong to each other in subfolders. The problem is that by convention the model class is namespaced into an according module.

E.g.

app/models/blog/post.rb
app/models/blog/comment.rb
app/models/user.rb

so that:

app/models/blog/post.rb

class Post < ActiveRecord
end

and not

class Blog::Post < ActiveRecord
end
A: 

I dont think that you can change this behaviour.

Lichtamberg
A: 

Until I find a better solution I've created a init.rb in the app/models folder:

app/models/init.rb

%w[blog].each do |folder|
  path = [File.dirname(__FILE__), folder, "*.rb"].join('/')
  Dir[path].each {|file| require file }  
end

Servers the purpose until now.

seb
A: 

Maybe you could look upon RailsEngines. It's not exactly what you need, but could gave you some ideas.

Other than that, if your script seems to work fine (you could also just read all the files on each subfolder on model and require them), I don't see any problem against it.

Yaraher
+6  A: 

We needed to do this, and there is a very simple way.

move your models into the sub-folders, and then tell rails to load files from all subfolders in your environment.rb file:

config.load_paths += Dir["#{RAILS_ROOT}/app/models/*"].find_all { |f| File.stat(f).directory? }

No namespacing required, and the models can be referred to as normal in your app

Tilendor
This doesn't work in Rails 3. Any ideas?
Vincent
Haven't gotten into rails 3 yet :(
Tilendor
A: 

this version of Tilendor's solution works with Rails 3

config.load_paths and RAILS_ROOT are deprecated in Rails 3, also you should put it in the config block of the config/application.rb, not environment.rb

config.autoload_paths += Dir["#{Rails.root.to_s}/app/models/*"].find_all { |f| File.stat(f).directory? }
chris_b