Jun 25, 2009
Organizing Models in Rails without Namespacing
I was doing some code cleanup and noticed we have over 50 models in our models directory. Not good. The first thing I thought was to add namespacing. I googled the topic and turns out namespacing models is a bad idea because of how Rails collapses the model namespaces. Adding sub directories is a better and cleaner solution. Read Josh Susser’s post on the topic.
To use sub directories, you must add the directories to Rails’ config.load_paths in your environment.rb
config.load_paths << "#{Rails.root}/app/models/profile"
To make this more flexible, you can use this snippet to add all sub directories:
#Add all sub directories in models to load paths
Dir.entries("#{Rails.root}/app/models").each do |file|
next if file.eql?('.') || file.eql?('..')
full_path = "#{Rails.root}/app/models/#{file}"
config.load_paths << full_path if File.directory?(full_path)
end