Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

module

ruby

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?

like image 220
Andrei Botalov Avatar asked Mar 26 '13 18:03

Andrei Botalov


1 Answers

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
like image 81
Arie Xiao Avatar answered Sep 17 '22 21:09

Arie Xiao