首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用包含同名类方法的模块扩展类

用包含同名类方法的模块扩展类
EN

Stack Overflow用户
提问于 2015-03-16 12:08:25
回答 2查看 374关注 0票数 0

我将ActiveRecord类扩展为描述这里这里的显著模式。我找不到一种方法来安全地让我的新包含类方法(extend_with_mod_aextend_with_mod_b)调用他们自己的类方法(bar)

代码语言:javascript
复制
require 'active_record'

module ModA
  extend ActiveSupport::Concern

  module ClassMethods

    def extend_with_mod_a
      puts "extending #{self} with ModA"
      bar
    end

    def bar
      puts "this is method bar of ModA"
    end

  end

end


module ModB
  extend ActiveSupport::Concern

  module ClassMethods

    def extend_with_mod_b
      puts "extending #{self} with ModB"
      bar
    end

    def bar
      puts "this is method bar of ModB"
    end

  end

end

ActiveRecord::Base.send :include, ModA
ActiveRecord::Base.send :include, ModB

class TestModel < ActiveRecord::Base

  extend_with_mod_a
  extend_with_mod_b

end

输出是

代码语言:javascript
复制
extending with ModA
this is method bar of ModB
extending with ModB
this is method bar of ModB

当然,调用哪个bar方法取决于ActiveRecord,包括调用顺序。我想在extend_with_mod_a方法定义中使用类似于extend_with_mod_a的东西

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-27 19:10:56

代码语言:javascript
复制
module ModA
  extend ActiveSupport::Concern

  module ClassMethods
    def bar
      puts "this is method bar of ModA"
    end

    # grab UnboundMethod of ModA::ClassMethods::bar
    a_bar = instance_method(:bar)

    # using define_method to capture a_bar
    define_method :extend_with_mod_a do
      puts "extending #{self} with ModA"
      # invoke ModA::ClassMethods::bar properly bound to the class being extended/included with ModA
      a_bar.bind(self).call
    end
  end
end
票数 0
EN

Stack Overflow用户

发布于 2015-03-16 13:54:07

尝试:prepend您的模块。

代码语言:javascript
复制
ActiveRecord::Base.send :prepend, ExtModule
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29076435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档