Skip to content

Instantly share code, notes, and snippets.

@bxt
Last active December 7, 2016 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bxt/b4da635da9aee12d6e7236147513e40f to your computer and use it in GitHub Desktop.
Save bxt/b4da635da9aee12d6e7236147513e40f to your computer and use it in GitHub Desktop.
Ruby's top level methods break encapsulation
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