Created
November 24, 2012 19:46
-
-
Save tubbo/4141173 to your computer and use it in GitHub Desktop.
making private methods private
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
# = Private Parts | |
# | |
# A little code experiment on making private methods in Ruby | |
# actually private. | |
# | |
# @tubbo - http://psychedeli.ca/ | |
class PrivateParts | |
def initialize | |
@boobs = "( . )( . )" | |
@butts = "( )( )" | |
@balls = "( )( )" | |
end | |
def exposure | |
peep_show | |
end | |
def send(method, *args) | |
if private_methods.include? method | |
raise NoMethodError.new("private method '#{method}' called for #{self}") | |
else | |
super(method, *args) | |
end | |
end | |
private | |
def peep_show | |
@boobs + @butts + @balls | |
end | |
end | |
require 'test/unit' | |
class PrivatePartsTest < Test::Unit::TestCase | |
def test_peep_show_cannot_be_called_outside_of_the_class | |
parts = PrivateParts.new | |
assert_raises(NoMethodError) { parts.peep_show } | |
assert_raises(NoMethodError) { parts.send(:peep_show) } | |
end | |
def test_peep_show_can_be_exposed_by_exposure | |
parts = PrivateParts.new | |
assert_equal "( . )( . )( )( )( )( )", parts.exposure | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Or, if you really want that method to be private, use I Told You it Was Private (implementation). 😉