[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Class methods and modules

Pedro Cardoso

7/13/2007 2:21:00 PM

Hello

I wan't to design a Module that defines some methods that I wan't as
class methods in the classes that includes them. Is it possible?

Thanks

--
Posted via http://www.ruby-....

3 Answers

Tim Pease

7/13/2007 2:43:00 PM

0

On 7/13/07, Pedro Cardoso <cardosojp@netcabo.pt> wrote:
> Hello
>
> I wan't to design a Module that defines some methods that I wan't as
> class methods in the classes that includes them. Is it possible?
>
> Thanks
>

module MyModule
module ClassMethods
def class_method_one( )
puts "you're in class method one"
end

def class_method_two( )
puts "you're in class method two"
end
end # module ClassMethods

def self.included( other )
other.extend ClassMethods if Class === other
end

def method_one( )
puts "you're in method one"
end
end

class C
include MyModule
end

C.new.method_one #=> you're in method one
C.class_method_one #=> you're in class method one
C.class_method_two #=> you're in class method two


Blessings,
TwP

Pedro Cardoso

7/13/2007 3:06:00 PM

0

Hi. Thanks!

I found another way.

Module MyModule
def m
end
end

class MyClass
extend MyDodule
end

MyClass.m

Can anyone explain the "job" of extend?

Thanks.

--
Posted via http://www.ruby-....

Stefan Rusterholz

7/13/2007 3:18:00 PM

0

Pedro Cardoso wrote:
> Hi. Thanks!
>
> I found another way.
>
> Module MyModule
> def m
> end
> end
>
> class MyClass
> extend MyDodule
> end
>
> MyClass.m
>
> Can anyone explain the "job" of extend?
>
> Thanks.

Extend includes the methods in the singleton class. E.g.
MyClass.extend(MyModue) is (almost) equivalent to:
class <<MyClass
include MyModule
end
Only almost because iirc a different callback is used.

Regards
Stefan

--
Posted via http://www.ruby-....