Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a class into multiple files in Ruby on Rails

I'm trying to split a large model into multiple files for logical organization. So i have two files:

model1.rb

class Model1 < ActiveRecord::Base
  before_destroy :destroying
  has_many :things, :dependent=>:destroy

  def method1
    ...
  end
  def method2
    ...
  end

end
require 'model1_section1'

model1_section1.rb

class Model1
  def method3
    ...
  end
  def self.class_method4
    ...
  end
end

but when the app loads, and there is a call to Model1.class_method4, i get:

undefined method `class_method4' for #<Class:0x92534d0>

i've also tried this for the require:

require File.join(File.dirname(__FILE__), 'model1_section1')

What am i doing wrong here?

like image 410
ilasno Avatar asked Mar 09 '11 04:03

ilasno


2 Answers

I know I'm answering this a little late, but I've just done this in one of my apps so thought I'd post the solution I used.

Let's this was my model:

class Model1 < ActiveRecord::Base

  # Stuff you'd like to keep in here
  before_destroy :destroying
  has_many :things, :dependent => :destroy

  def method1
  end
  def method2
  end

  # Stuff you'd like to extract
  before_create :to_creation_stuff
  scope :really_great_ones, #...

  def method3
  end
  def method4
  end
end

You can refactor it to:

# app/models/model1.rb
require 'app/models/model1_mixins/extra_stuff'
class Model1 < ActiveRecord::Base

  include Model1Mixins::ExtraStuff

  # Stuff you'd like to keep in here
  before_destroy :destroying
  has_many :things, :dependent => :destroy

  def method1
  end
  def method2
  end
end

and:

# app/models/model1_mixins/extra_stuff.rb
module Model1Mixins::ExtraStuff

  extend ActiveSupport::Concern

  included do
    before_create :to_creation_stuff
    scope :really_great_ones, #...
  end

  def method3
  end
  def method4
  end
end

It works perfectly thanks to the extra cleanliness that ActiveSupport::Concern gives you. Hope this solves this old question.

like image 165
iHiD Avatar answered Sep 21 '22 15:09

iHiD


Here's an article that does a good job of proposing solutions to this problem:

http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

like image 38
Kevin Bedell Avatar answered Sep 22 '22 15:09

Kevin Bedell