Can I enable / extend a module, but mark all included / extended methods as private?

Say I have a class Aand a module B. I would like to include / extend Bin A, but mark the included / extended methods as private (so that they are not accessible to callers A, but will be available inside the methods A).

How to include Bin A, but mark all included methods as private?

+5
source share
1 answer

Include and then explicitly make all included methods private?

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

You can Moduleadd a monkey patch private_includeand 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, *modules)
      modules.each do |mod|
        self.send(:private, *mod.instance_methods)
      end
    end
  end
end
+6
source

All Articles