Created
June 24, 2009 12:53
-
-
Save trans/135232 to your computer and use it in GitHub Desktop.
True Public/Private Access
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
# Playing around with an idea for true public vs. private access. | |
# | |
# Y is a subclass of X. | |
# x is an instance of X (ie. a public interface) | |
# Likewise y is an instance of Y. | |
# | |
# y | |
# | | |
# V | |
# Y:private -> Y:protected -> Y:public x | |
# | | | |
# V V | |
# X:private -> X:protected -> X:public | |
# | |
# So Y can't "see" X:private. | |
# Nor can x "see" X:private or X:protected. | |
# | |
# The following example, is only partially functional because of the way Ruby | |
# works. It is not possible to actualy use #private, #protected or #public to | |
# enforce the visibility b/c Ruby does'nt treat them as truely separate | |
# namespaces in this regard. | |
module X_private | |
# private | |
def private_hello | |
"Private Hello." | |
end | |
def super_hello | |
"->Super Private Hello" + (defined?(super) ? super : '') | |
end | |
end | |
module X_public | |
# public | |
def public_hello | |
"Public Hello!" | |
end | |
def super_hello | |
"->Super Public Hello" + (defined?(super) ? super : '') | |
end | |
def privy_hello | |
private_hello | |
end | |
end | |
class X #< SuperClass | |
class << self | |
alias :__new :new | |
def new(*args,&blk) | |
o = __new(*args,&blk) | |
o.extend X_private if self == X | |
o | |
end | |
end | |
include X_public | |
# protected | |
def protected_hello | |
"Protected Hello?" | |
end | |
def super_hello | |
"->Super Protected Hello" + (defined?(super) ? super : '') | |
end | |
end | |
class Y < X | |
def call_me | |
private_hello #=> should error | |
end | |
end | |
x = X.new | |
p x.public_hello | |
p x.privy_hello | |
p x.super_hello | |
y = Y.new | |
p y.super_hello | |
p y.call_me |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment