Skip to content

Instantly share code, notes, and snippets.

@pocke
Created March 10, 2018 01:45
Show Gist options
  • Select an option

  • Save pocke/76387ab0a719f2f7a93d7ce1b2f87567 to your computer and use it in GitHub Desktop.

Select an option

Save pocke/76387ab0a719f2f7a93d7ce1b2f87567 to your computer and use it in GitHub Desktop.
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