Skip to content

Instantly share code, notes, and snippets.

@tubbo
Created November 24, 2012 19:46
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 tubbo/4141173 to your computer and use it in GitHub Desktop.
Save tubbo/4141173 to your computer and use it in GitHub Desktop.
making private methods private
# = 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
@roryokane
Copy link

Or, if you really want that method to be private, use I Told You it Was Private (implementation). 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment