Class methods and modules

P

Pedro Cardoso

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
 
T

Tim Pease

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
 
P

Pedro Cardoso

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.
 
S

Stefan Rusterholz

Pedro said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,311
Members
47,985
Latest member
kazewi

Latest Threads

Top