Ruby:实现acts_as

时间:2015-07-01 08:04:57

标签: ruby-on-rails ruby module include rails-engines

我想实现一个acts_as。

这将是这样的:

Module Organisable
  def acts_as_organisable
    send :include, InstanceMethods
    has_many ...
    before_destroy ...
    ??
  end
  module InstanceMethods
    def method1
    end    

    def method2
    end
  end
end

它将被用作:

def myClass < ActiveRecord::Base
    acts_as_organisable

end

我尝试了但它确实有效。如果可能的话,我也想传递参数(acts_as_organisable(param))。

此模块必须放在另一个引擎中。

对于我认为的文件组织:

MyEngine
   Models
     MyEngine
        MyEngineClass
     Organisable
        Organisable

但不确定。

1 个答案:

答案 0 :(得分:0)

您需要将模块添加到延迟加载挂钩。像这样:

ActiveSupport.on_load(:active_record) do
  include Organisable
end

有关详细信息,请参阅Understanding Ruby and Rails: Lazy load hooks