0

如果我有这样的课,

class A < ActiveRecord::Base
  include ExampleModule
end

class B < ActiveRecord::Base
  include ExampleModule
end

module ExampleModule
  module ClassMethods
    ...
  end      

  def included(base)
    ...
  end
end

在将这个模块引用到这些类中的任何一个中时,如何在 ExampleModule 中获取对 A 类或 B 类的引用?我问这个问题是因为我想做一些事情,比如通过包含 ExampleModule 来将has_one :associationafter_create :do_something添加到类 A 或 B 中,如下所示。

class A < ActiveRecord::Base
  include ExampleModule
end

class B < ActiveRecord::Base
  include ExampleModule
end

module ExampleModule
  has_one :association
  after_create :do_something      

  module ClassMethods
    ...
  end      

  def included(base)
    ...
  end
end

有没有更好的方法来做到这一点?谢谢!

4

2 回答 2

1

如果您扩展ActiveSupport::Concern,您应该能够在模块为included

module ExampleModule

  extend ActiveSupport::Concern

  def do_something
    # ...
  end

  included do
    has_one :association
    after_create :do_something      
  end
end
于 2012-07-18T00:22:58.313 回答
1

If what you're wanting to do is call has_one or after_create depending on which class is including the module you can do this

module Extender
  def self.included(base)
    if base.name == A.name
       # do stuff for A
       has_one :association
    elsif base.name == B.name
       # do stuff for B
       after_create :do_something
    end
  end
end
于 2012-07-24T12:08:03.893 回答