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

前端之家收集整理的这篇文章主要介绍了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给你的额外清洁.希望能解决这个老问题.

猜你在找的Ruby相关文章