Call overwritten method of included module?

J

Joshua Muheim

Hi all

module MyModule
def my_method
return "my module rocks!"
end
end

class MyClass
include(MyModule)

def my_method
return "my class rocks!"
end
end

Is there a way to call MyModule::my_method from within MyClass? "super"
sadly doesn't work...

Thanks a lot
Josh
 
M

Morton Goldberg

Hi all

module MyModule
def my_method
return "my module rocks!"
end
end

class MyClass
include(MyModule)

def my_method
return "my class rocks!"
end
end

Is there a way to call MyModule::my_method from within MyClass?
"super"
sadly doesn't work...

Perhaps this will do:

<code>
module MyModule
def my_method
"my module rocks!"
end
end

class MyClass
include MyModule
alias module_method my_method
def my_method
"#{module_method}\nmy class rocks!"
end
end

puts MyClass.new.my_method
</code>

<result>
my module rocks!
my class rocks!
</result>

Regards, Morton
 
D

Daniel Sheppard

module MyModule
def my_method
return "my module rocks!"
end
end
=20
class MyClass
include(MyModule)
=20
def my_method
return "my class rocks!"
end
end
=20
Is there a way to call MyModule::my_method from within=20
MyClass? "super"
sadly doesn't work...

You'd need to alias the old method:

class MyClass
include(MyModule)
alias :eek:ld_my_method :my_method
def my_method
old_my_method
end
end

(If you're using rails/activesupport, you'd probably use
alias_method_chain to simplify things)

Dan.
 
J

Joshua Muheim

(If you're using rails/activesupport, you'd probably use
alias_method_chain to simplify things)

Dan.

Thanks! Especially for the alias_method_chain hint! :)
 
R

Robert Dober

Hi all

module MyModule
def my_method
return "my module rocks!"
end
end

class MyClass
include(MyModule)

def my_method
return "my class rocks!"
end
end

Is there a way to call MyModule::my_method from within MyClass? "super"
sadly doesn't work...
super shall work and indeed does
module MyModule
def my_method
return "my module rocks!"
end
end

class MyClass
include(MyModule)

def my_method

return [ super, "my class rocks!" ].join("\n")
end
end

puts MyClass.new.my_method

HTH
Robert
 

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
473,774
Messages
2,569,596
Members
45,135
Latest member
VeronaShap
Top