Last active
December 7, 2016 08:57
-
-
Save bxt/b4da635da9aee12d6e7236147513e40f to your computer and use it in GitHub Desktop.
Ruby's top level methods break encapsulation
This file contains 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
def a_random_method_not_defined_in_a_class | |
puts self.class # outputs ExampleClass | |
puts @a_private_member # works | |
end | |
class ExampleClass | |
def initialize(a_private_member) | |
@a_private_member = a_private_member | |
end | |
def a_method | |
a_random_method_not_defined_in_a_class | |
end | |
end | |
# This calls a_random_method_not_defined_in_a_class like a private method of ExampleClass's | |
ExampleClass.new("I'm a private member leaked to an outside method!").a_method | |
# This is because top-level methods are actually privte methods from Obejct | |
puts Object.private_method_defined?(:a_random_method_not_defined_in_a_class) # true | |
# And classes inherit from Object by default | |
puts ExampleClass.ancestors.include?(Object) # true | |
# Tested with | |
# * ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14] | |
# * ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-darwin15] | |
# * ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin15] | |
# * ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin16] | |
# * ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15] | |
# using this: | |
# for RUBY_VERSION in $(rvm list strings); do rvm use $RUBY_VERSION; ruby --version; ruby encapsulation-problem.rb; done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment