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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 将类分成Ruby on Rails中的多个文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图将大型模型分成多个文件进行逻辑组织.所以我有两个文件

model1.rb

  1. class Model1 < ActiveRecord::Base
  2. before_destroy :destroying
  3. has_many :things,:dependent=>:destroy
  4.  
  5. def method1
  6. ...
  7. end
  8. def method2
  9. ...
  10. end
  11.  
  12. end
  13. require 'model1_section1'

model1_section1.rb

  1. class Model1
  2. def method3
  3. ...
  4. end
  5. def self.class_method4
  6. ...
  7. end
  8. end

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

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

我也试过这个要求:

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

我在这里做错了什么?

解决方法

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

让我们这是我的模特儿:

  1. class Model1 < ActiveRecord::Base
  2.  
  3. # Stuff you'd like to keep in here
  4. before_destroy :destroying
  5. has_many :things,:dependent => :destroy
  6.  
  7. def method1
  8. end
  9. def method2
  10. end
  11.  
  12. # Stuff you'd like to extract
  13. before_create :to_creation_stuff
  14. scope :really_great_ones,#...
  15.  
  16. def method3
  17. end
  18. def method4
  19. end
  20. end

您可以将其重构为:

  1. # app/models/model1.rb
  2. require 'app/models/model1_mixins/extra_stuff'
  3. class Model1 < ActiveRecord::Base
  4.  
  5. include Model1Mixins::ExtraStuff
  6.  
  7. # Stuff you'd like to keep in here
  8. before_destroy :destroying
  9. has_many :things,:dependent => :destroy
  10.  
  11. def method1
  12. end
  13. def method2
  14. end
  15. end

和:

  1. # app/models/model1_mixins/extra_stuff.rb
  2. module Model1Mixins::ExtraStuff
  3.  
  4. extend ActiveSupport::Concern
  5.  
  6. included do
  7. before_create :to_creation_stuff
  8. scope :really_great_ones,#...
  9. end
  10.  
  11. def method3
  12. end
  13. def method4
  14. end
  15. end

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

猜你在找的Ruby相关文章