加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 我可以包含/扩展模块,但将所有包含/扩展方法标记为私有

发布时间:2020-12-17 03:22:54 所属栏目:百科 来源:网络整理
导读:比方说,我有一个A类和一个模块B.我想要包含/扩展B到A但是将包含/扩展方法标记为私有(因此它们不会被A的调用者访问,但可以在A的方法中访问一个). 如何将B包含在A中,但将所有包含的方法标记为私有? 解决方法 包含然后明确地将所有包含的方法设为私有? class
比方说,我有一个A类和一个模块B.我想要包含/扩展B到A但是将包含/扩展方法标记为私有(因此它们不会被A的调用者访问,但可以在A的方法中访问一个).

如何将B包含在A中,但将所有包含的方法标记为私有?

解决方法

包含然后明确地将所有包含的方法设为私有?

class A
  include B
  private *B.instance_methods
  extend B
  class << self
    private *B.instance_methods
  end
end

您可以通过猴子补丁模块添加private_include和private_extend:

class Module
  def private_include *modules
    class_eval do
      self.send(:include,*modules)
      modules.each do |mod|
        self.send(:private,*mod.instance_methods)
      end
    end
  end

  def private_extend *modules
    singleton = class << self; self end
    singleton.instance_eval do
      self.send(:include,*mod.instance_methods)
      end
    end
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读