Created
March 10, 2018 01:45
-
-
Save pocke/76387ab0a719f2f7a93d7ce1b2f87567 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module PrivateBlock | |
| def private(*args, &block) | |
| return super unless block_given? | |
| begin | |
| methods = [] | |
| mod = Module.new do | |
| define_method :method_added do |name| | |
| super(name).tap do | |
| methods << name | |
| end | |
| end | |
| end | |
| self.singleton_class.prepend mod | |
| block.call | |
| ensure | |
| private(*methods) | |
| mod.remove_method :method_added | |
| end | |
| end | |
| end | |
| class Module | |
| prepend PrivateBlock | |
| end | |
| class A | |
| private do | |
| def foo | |
| p 'foo' | |
| end | |
| end | |
| def bar | |
| p 'bar' | |
| end | |
| end | |
| A.new.foo rescue p $! | |
| A.new.__send__(:foo) | |
| class B | |
| def self.method_added(name) | |
| puts "#{name} is defined!" | |
| end | |
| private do | |
| def foo | |
| p 'foo' | |
| end | |
| end | |
| def bar | |
| p 'bar' | |
| end | |
| end | |
| B.new.foo rescue p $! | |
| B.new.bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment