views:

172

answers:

3

Usually there are a lot of models in a Ruby on Rails project, so:

  1. Is it a good practice to namespace them (in modules/folders)? What are the downsides? EG:

    • Shop
      • category.rb
      • details.rb
    • Products
      • category.rb
      • base.rb

etc

(instead of ShopCategory, to have Shop::Category?)

  1. Should also the controllers be namespaced in the same manner?

Thank you

A: 

I'm doing that a lot.
So yes I think that's something you should do.

It'll be be a lot easier for you to view models if you have them subdivided in subdirectories instead of having them all in the same one.

The same recommendation is also valid for your controllers and your views.

Damien MATHIEU
Thank you, Damien.That was what i was talking about, splitting them into subfolders (and, of course, to respect rails conventions, including them into the corresponding modules).
Vlad Zloteanu
+2  A: 

I've recently found this post but back from 2007 by Pratik Naik. Says there namespace in models doesn't really resemble databases. Uses something like below. Even there's a quote from DHH too.

Rails::Initializer.run do |config|
  # Your existing stuff
  config.load_paths << "#{RAILS_ROOT}/app/models/pets"
end

http://m.onkey.org/2007/12/9/namespaced-models

p/s: I don't know whether the post is still relevant or not, just something I found recently when I wanted namespaces in my models.

Ed
A: 

I recommend using single table inheritance for your category model. For example:

Category < ActiveRecord::Base end

ShopCategory < Category end

ProductCategory < Category end

Shop < ActiveRecord::Base
  belongs_to :shop_category
end

Product < ActiveRecord::Base
  belongs_to :product_category
end

This will encapsulate commonly used category behaviour and attributes into a single model and could allow you to reuse a lot of code and have a single controller. Using namespacing only makes sense to me when the underlying classes have some sort of data/functionality in common. (example: acts_as_versioned creates a Version class namespaced under the model)

Roel
That's not what STI is intended for. And it doesn't makes your models more readable at all, all the contrary. I wouldn't do that.
Damien MATHIEU