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

module, ruby

Solution

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 monkey patch `Module` to add `private_include` and `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

Problem

Say, I have a class `A` and a module `B`. I'd want to include/extend `B` into `A` but mark included/extended methods as private (so they won't be accessible to callers of `A` but will be accessible inside methods of `A`). How can I include `B` into `A` but mark all included methods as private?

Original source