1

Some of my AR classes are starting to... bulge around the waist. I'm starting to think it might be time to put them on a diet. Probably the biggest concern I have is that there's just so much code in one file, I'm considering breaking out validations, associations and groups of related methods into modules. Are there any other alternatives I haven't considered?

I'd also like to do the same thing with my tests (I'm using shoulda with test/spec if that makes a different)...

Your thoughts would be greatly appreciated.

jonnii
  • 28,019
  • 8
  • 80
  • 108

2 Answers2

2

I'm familiar with your problem. Some models in my projects were also getting too big to work pleasantly with them. I found a small piece of code (I think on PaulBarry.com) which enables you to split your models into several files.

concerned_with makes it possible to place parts of your model in a subfolder. You put, for example, the following line in your original model:

class User < ActiveRecord::Base
    concerned_with :validation
end

Then you create a file in 'models/user/validation.rb' which contains your validations:

class User
    validates_presence_of :username
end

Just put this code into an initializers file in your Rails project and you can use this nice feature!

class << ActiveRecord::Base
  def concerned_with(*concerns)
    concerns.each do |concern|
      require_dependency "#{name.underscore}/#{concern}"
    end
  end
end
Edwin V.
  • 1,327
  • 8
  • 11
0

It's quite normal to extract everything, or, most-common behaviour with associations into plugins with class methods like "acts_as_fat_model".

In general one of rails mvc idioms is "Fat models - skinny controllers". It's a good sign that your models (and not controllers) are fat.

Eimantas
  • 48,927
  • 17
  • 132
  • 168
  • I'm a preacher of the fat model/thin controller church. The problem with fat models is that they're still fat =) – jonnii Sep 18 '09 at 18:36