logo       

Re: Q) about singleton methods and access control: msg#01146

lang.ruby.general

Subject: Re: Q) about singleton methods and access control


"Bennett, Patrick" <Patrick.Bennett@xxxxxxxx> wrote in message
news:58A40B582A73F54AB5D8739C0678F3A802320696@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
..
> This is what I'd "like" to do:
> class A
>
> def initialize()
> @varInternalOnly = 'test'
> end
>
> def A.createSpecialA()
> testObj = A.new
> testObj.internalHelperMethod()

internalHelperMethod is an ``instance method'' not a Class method
(see below). Also note quite generally that private methods can only
be invoked in the implicit receiver ( = self ) form

some_private_method(*args)

Note that even

self.some_private_method(*args).

you will get you into trouble. Anyway, as the short term fix you can
simply write

testObj.send(: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.

Note that C++ static (class) method are quite different to Ruby's class
methods
(disregarding the fact that they share the same name and mainly due to the
fact that in C++ does not have Class objects). In C++ you can invoke
a class (== static) method in the receiver form

SomeClass::class_meth(..)

or instance form

any_class_instance.class_meth(..)


Possible receivers of a Ruby class method

def SomeClass.class_meth(..)
# body
end

(in Ruby terminology ``a singleton method of the Class instance
SomeClass'') is the Class instance SomeClass itself or a Class
descendant of SomeClass.


/Christoph





<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise