[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Delegating class methods

Michael Malone

3/1/2009 8:58:00 PM

class Klass

extend Forwardable

def_delegators :@object :method1, :method2, :method3

def initialize
@object = SomeKlass.new
end

end
> Hi all,
>
> how would you forward calls from class methods to a class atribute?
> Like in:
>
> class Foo
> @@hash = {}
>
> def self.size
> @@hash.size
> end
> end
>
> I have to delegate a fairly large number of calls to an attribute. I'm
> currently using method_missing, but I was wondering if there was a
> cleaner way to do that as the method names are known at load time. I
> didn't find any using the standard library. Perhaps using some
> metaprogramming.
>
> Thanks!
>
>


=======================================================================
This email, including any attachments, is only for the intended
addressee. It is subject to copyright, is confidential and may be
the subject of legal or other privilege, none of which is waived or
lost by reason of this transmission.
If the receiver is not the intended addressee, please accept our
apologies, notify us by return, delete all copies and perform no
other act on the email.
Unfortunately, we cannot warrant that the email has not been
altered or corrupted during transmission.
=======================================================================


1 Answer

lasitha

3/2/2009 5:20:00 AM

0

On Mon, Mar 2, 2009 at 2:27 AM, Michael Malone
<michael.malone@tait.co.nz> wrote:
> On Mon, Mar 2, 2009 at 2:03 AM, abc <arcadiorubiogarcia@gmail.com> wrote:
>>
>> how would you forward calls from class methods to a class atribute?
>> [...]
>>
>> I have to delegate a fairly large number of calls to an attribute. [...]
>
> class Klass
> extend Forwardable
> def_delegators :@object :method1, :method2, :method3
>
> def initialize
> @object = SomeKlass.new
> end
> end

No, that would forward to an instance variable and only work with
Klass instances.

If the OP doesn't mind using a singleton class variable instead of a
class variable [1], then we can still use forwardable:

class Foo
@hash = {}
class << self
extend Forwardable
def_delegators :@hash, :[], :[]=, :size
end
end

Foo[:bar] = 'baz'
Foo.size #=> 1

Solidarity,
lasitha

[1] Generally a good idea anyway, right?