This is what I’d “like” to do:
class A
def initialize()
@varInternalOnly = ‘test’
end
def A.createSpecialA()
testObj = A.new
testObj.internalHelperMethod() # [Fails because internalHelperMethod is private - even though this is a class A method. :]
return testObj
end
private
def internalHelperMethod()
@varInternalOnly = ‘foo’
end
end
A.createSpecialA()
I would like to have my singleton methods (like in C++) have access to protected/private members of its own class. Without this, it’s not possible to have static (singleton) class methods
act as helpers (or in my case, alternative constructors) and access ‘private’ methods/variables of its own class type. To me at least, this reduces the usability of the access-control modifiers quite a bit.
···
-----Original Message-----
From: Christoph [mailto:chr_news@gmx.net]
Sent: Monday, August 12, 2002 3:09 PM
To: ruby-talk ML
Subject: Re: Q) about singleton methods and access control
“Patrick Bennett” wrote,
…
Recently, I was rather surprised to learn that singleton methods aren’t
able to access protected/private members of a class.
Hm I not quite sure to what access problem you are
refering to. Could illustruted this in an example. Afaikt
every thing seems to be oaky - for example, I get the
output
“fine”
“fine”
“fine”
protected method sometimes_fine' called for #<B:0x284ab10> protected method
bad’ called for #<B:0x284ab10>
me everything seems to be okay - for example
when running the the test script
illustrate protected
class A
def okay(x) x.fine end
def sometimes_okay(x) x.sometimes_fine end
def never_okay(x) x.bad end
def sometimes_fine; p "fine" end
protected
def fine; p "fine" end
end
class B < A
protected
def bad
p “bad”
end
end
a = A.new
b = B.new
a.okay b
class << a
def okay(x)
x.fine
end
end
a.okay b
a.sometimes_okay b
class << b
protected
def sometimes_fine
super
end
end
begin
a.sometimes_okay b
rescue NameError => mes
puts mes
end
begin
a.never_okay b
rescue NameError => mes
puts mes
end
Unfortunately, I’d like to have a class with multiple singleton
‘constructor’ methods. Each would return a new instance of the class,
initialized properly. None of these actions would really make sense to
have in Initialize.
Well, if the singleton method can’t access protected/private
members/methods of the class, then how can I have protected portions of
the class (to avoid problems with normal users of the class), and still
have
a signleton method create intiailized instances of the class?Hopefully I’m completely missing the boat on this one and there’s a
solution to my problem.
Hm, I am quite sure that this problem can be resolved (in the
worst case just use the “send(:name_of_private_method,*meth_args)
trick”- Again could illustrate your problem with a code example?
/Christoph