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

About tommychheng
I write a tech blog at http://tommy.chheng.com

4 Responses to Organizing Models in Rails without Namespacing

  1. Nicola says:

    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.

  2. tommy says:

    Hi Nicola,
    What is your folder structure for your models folder?
    What did you add to your environment.rb file?

  3. Nicola says:

    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!

  4. tommy says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.