views:

53

answers:

2

Hello friends!

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.

A: 

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
I'm a preacher of the fat model/thin controller church. The problem with fat models is that they're still fat =)
jonnii
+1  A: 

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.
This is a good idea, however wouldn't the validation concern be: class Validation?
jonnii
Ah, not it shouldn't be because you're reopening the user class. Sorry, ignore that!
jonnii
I wish I could give you another upvote for this...
jonnii