ruby-on-rails – 将类分成Ruby on Rails中的多个文件

我试图将大型模型分成多个文件进行逻辑组织.所以我有两个文件

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

但是当应用程序加载时,并且有一个对Model1.class_method4的调用,我得到:

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

我也试过这个要求:

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

在这里做错了什么?

解决方法

我知道我稍晚回答这个问题,但是我刚才在我的一个应用程序中做了这个,所以以为我会发布我使用的解决方案.

让我们这是我的模特儿:

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

您可以将其重构为:

# 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

和:

# 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

它的工作完美感谢ActiveSupport :: Concern给你的额外清洁.希望能解决这个老问题.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...