Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to structure models into subfolders without creating submodules

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 
like image 469
seb Avatar asked Sep 18 '09 15:09

seb


2 Answers

Here is what I used for Rails 3:

config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')] 

This configuration tells Rails to scan all the app/models subfolders recursively and load all found models. No namespacing required.

like image 197
Ion Br. Avatar answered Oct 16 '22 22:10

Ion Br.


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

like image 23
Tilendor Avatar answered Oct 17 '22 00:10

Tilendor