Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
class Module
def wrap_package_private name
wraped_method = instance_method(name)
define_method(name) do |*args|
# check
puts "checking package_private: #{name}"
if true
e = NoMethodError.new("package private method is called from outside of the package")
e.set_backtrace caller
raise e
end
# call original
wraped_method.bind(self).call(*args)
end
end
private :wrap_package_private
def package_private *methods
if methods.length > 0
methods.each do |m|
wrap_package_private m
end
else
set_current_visibility :package_private
end
end
def set_current_visibility visi
@current_visibility = visi
@caller_of_current_visibility_set_method = caller[2..-1]
end
private :set_current_visibility
def method_added name
if @current_visibility
current_caller = caller[1..-1]
if current_caller == @caller_of_current_visibility_set_method
case @current_visibility
when :package_private
wrap_package_private name
end
end
end
end
alias __public__ public
def public *args
@current_visibility = nil
__public__ *args
end
alias __protected__ protected
def protected *args
@current_visibility = nil
__protected__ *args
end
alias __private__ private
def private *args
@current_visibility = nil
__private__ *args
end
end
class Neko
def public_method1
puts "public_method1"
end
package_private
def package_private_method1
puts "package_private_method1"
end
def package_private_method2
puts "package_private_method2"
end
public
def public_method2
puts "public_method2"
end
end
class Neko
def public_method3
puts "public_method3"
end
end
Neko.new.public_method1
Neko.new.public_method2
Neko.new.public_method3
Neko.new.package_private_method1
Neko.new.package_private_method2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment