Created
October 13, 2014 05:12
-
-
Save ifyouseewendy/ed64dc884751660dc1b2 to your computer and use it in GitHub Desktop.
Check the visibility of private and protected mixined from module. Example from http://www.treibstofff.de/2009/08/07/ruby-visibility-of-private-and-protected-module-methods-when-mixed-into-a-class/
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 MyMethods | |
def my_public_method | |
puts "Public" | |
end | |
protected | |
def my_protected_method | |
puts "Protected" | |
end | |
private | |
def my_private_method | |
puts "Private" | |
end | |
end | |
class MyClass | |
include MyMethods | |
def invoke_my_protected_method | |
my_protected_method | |
end | |
def invoke_my_private_method | |
my_private_method | |
end | |
end | |
class MyInheritedClass < MyClass | |
def invoke_my_protected_method_from_subclass | |
my_protected_method | |
end | |
def invoke_my_private_method_from_subclass | |
my_private_method | |
end | |
end | |
mc = MyClass.new | |
mc.my_public_method | |
begin | |
mc.my_protected_method | |
rescue NoMethodError | |
puts "Unable to call a protected method." | |
end | |
begin | |
mc.my_private_method | |
rescue NoMethodError | |
puts "Unable to call a private method." | |
end | |
mc.invoke_my_protected_method | |
mc.invoke_my_private_method | |
mic = MyInheritedClass.new | |
mic.invoke_my_protected_method_from_subclass | |
begin | |
mic.invoke_my_private_method | |
rescue NoMethodError | |
puts "Unable to call a private method of the parent class." | |
end | |
##### OUTPUT | |
# Public | |
# | |
# Unable to call a protected method. | |
# | |
# Unable to call a private method. | |
# | |
# Protected | |
# | |
# Private | |
# | |
# Protected | |
# | |
# Private |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment