【问题标题】:Rails/Ruby Mixin brings unwanted other class methodsRails/Ruby Mixin 带来了不需要的其他类方法
【发布时间】:2011-08-25 17:39:15
【问题描述】:

只是希望有人可以为我解释一下..

我有一个导入模块的站点类:

网站

class Site < ActiveRecord::Base  
 include TrackableChanges  
 ...

在 trackable_changes.rb 中

我有这个代码..

module TrackableChanges
  include ActiveSupport::Callbacks

  def self.included(base)
      # Initialize module.
      base.has_many :change_requests, :as => :model, :dependent => :destroy
      #Callbacks
      base.before_save :before_save_change_request
      base.after_save :after_save_change_request
      base.before_destroy :before_destroy_change_request

      Facility

  end 
...

Facility的引用真的让我很困惑(我在这里放了一个微不足道的引用......)。基本上在 Facility.rb 我有这个..

class Facility < ActiveRecord::Base
  acts_as_citier

acts_as_citier 看起来有点像这样:

module Citier
  def self.included(base) 
    # When a class includes a module the module’s self.included method will be invoked.
    base.send :extend, ClassMethods
  end
end

ActiveRecord::Base.send :include, Citier

现在.. 只需在我的初始模块中引用 Facility,它就会转到acts_as_citier gem 并扩展我的 Site 类的 ActiveRecord。我想要为我的设施使用acts_as_citier gem,但不是为我的站点使用。

任何人都可以帮助阻止这种包括引入这个不需要的参考的线索!?

编辑

如果没有它通过引用 gem act_as_citier 引入在 Facility 中定义的 ActiveRecord 类添加,我似乎根本无法引用该类 Facility

城市这样做...

ActiveRecord::Base.send :include, Citier

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:
class Facility < ActiveRecord::Base
  #attr_accessible :name, :type, :facility_type_id, :accessibility_id, :tldc_id, :site_id, :tldc_approved  

  acts_as_citier if self.to_s == 'Facility' #Protects other classes from accidently getting the AR additions

向 include 添加条件会阻止acts_as_citier gem 扩展任何引用“Facility”的类。

我假设我的 Site 类上的包含 > 贯穿模块 > 当它遇到对 Facility 类的引用时 > 贯穿 Facility.rb > 贯穿acts_as_citier 然后点击延伸到活动记录行。它帮助我记住了 .rb 文件的每个部分都是可执行文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2016-06-12
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    相关资源
    最近更新 更多