Skip to content

Instantly share code, notes, and snippets.

@f3r
Created May 11, 2015 04:02
Show Gist options
  • Save f3r/4db341f5e624f56908f3 to your computer and use it in GitHub Desktop.
Save f3r/4db341f5e624f56908f3 to your computer and use it in GitHub Desktop.
visibility-test.rb
class ParentClass
def public_method
puts '[works] parent # public'
protected_method
end
protected # Can only be called from within the methods
def protected_method
puts '[works] parent # protected'
end
private
def private_method
puts '[works] parent # private'
end
end
class SubClass < ParentClass
def test_protected
protected_method rescue puts "[fails] subclass_instance # protected"
self.protected_method rescue puts "[fails] subclass_instance # self.protected"
end
def test_private
private_method rescue puts "[fails] subclass_instance # private" # implicit
self.private_method rescue puts "[fails] subclass_instance # self.private" # explicit
end
end
puts "="*40
puts "Calling from Parent Instance"
puts "="*40
parent = ParentClass.new
parent.public_method rescue puts "[fails] parent_instance # public"
parent.protected_method rescue puts "[fails] parent_instance # protected"
puts
puts "="*40
puts "Calling from Child Instance"
puts "="*40
child = SubClass.new
child.test_protected
child.test_private
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment