加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 21:28:48 所属栏目:百科 来源:网络整理
导读:我试图将大型模型分成多个文件进行逻辑组织.所以我有两个文件: model1.rb class Model1 ActiveRecord::Base before_destroy :destroying has_many :things,:dependent=:destroy def method1 ... end def method2 ... endendrequire 'model1_section1' model
我试图将大型模型分成多个文件进行逻辑组织.所以我有两个文件:

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给你的额外清洁.希望能解决这个老问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读