Tommy Chheng

Icon

All Things Programming!

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

Category: Ruby

Tagged:

  • tommy
    My guess is that there could be a typo, config.load_paths = ITEM here

    You can do a puts config.load_paths at the end of the environment.rb and check the console to see if the folders are being added.
  • By now I have only a single folder ("item") with all classes (STI included) .
    Talking about environment.rb I've tried with your (and others) generic version, now with this simple statement:
    config.load_paths += %W( #{RAILS_ROOT}/app/models/item )
    but nothing seems work...

    Very strange!
  • tommy
    Hi Nicola,
    What is your folder structure for your models folder?
    What did you add to your environment.rb file?
  • Hi tommy,
    I'm using Rails 2.3.2 and seems that there is no way to make work the snippet...

    Rails wants that I define namespaces for all the classes in the subdirectory...is there another config to do?

    Thanks,
    Nicola.
blog comments powered by Disqus