views:

34

answers:

1

Hello,

I have this method (50+ lines) in one of my models, I prefer not having to scroll so much and not losing my cursor sometimes because of its taking up so much space. I wonder if I can put it away in a separate file and sort of include it in the model instead.

Thanks!

+3  A: 

You can put it into a module and include it (mix it in) to your model class. For example:

app/models/my_long_method.rb
  module MyLongMethod
    def my_long_method
      ....
    end
  end

app/models/my_class.rb
  class MyClass < ActiveRecord::Base
    include MyLongMethod
  end

If your method really is that long though you might want to consider breaking it down into smaller sections as methods in that module too.

module MyLongMethod
  def my_long_method
    first_part
    second_part
  end

  private

  def first_part
    ...
  end

  def second_part
    ...
  end
end
Shadwell
Good answer. Relevant link for the last part: http://www.refactoring.com/catalog/extractMethod.html
troelskn
Thanks Shadwell and Troeskn. One last question to clear one thing up: does the module .rb file have to be in the same dir as the model which will 'include' it?
Nik
No, it doesn't have to. It just needs to be available in the load path. If you put it in a subdirectory you'll either need to put that subdirectory on the load path or use a namespace. E.g. `module SubDir::MyLongMethod`.
Shadwell
I have just tried this, but I get the error: app/models/line_item.rb:4:in `<class:LineItem>': uninitialized constant LineItem::HandyMethods (NameError)......I have placed the handy_methods.rb in the lib dir
Nik
You may need to `require 'line_item/handy_methods'` at the top of your model if the module is in the lib directory. Under app/blah it Rail should figure out where it is but I don't think that works for /lib.
Shadwell
@Shadwell, You're right. I just searched around and found that Rails 3 no longer auto-load files in lib. Thanks again!
Nik