Preferred way to overwrite an object method?

B

blogger

I have an app with source code I really don't want to touch, which has
an object method I want to be able to overwrite in a certain task.
(No need to restore the function.) My current technique is as
follows:

In the application:
class C
def m
puts "barf"
end
end

In my module file:
module M
def self.included(mod)
mod.module_eval <<-EOF
def m
puts "c001c0de"
end
EOF
end
end

In the rake file:
C:send:)include, M)

Now I REALLY don't like module_eval(string). Is there a preferred
method to achieve this result?
 
R

Robert Dober

I have an app with source code I really don't want to touch, which has
an object method I want to be able to overwrite in a certain task.
(No need to restore the function.) My current technique is as
follows:

In the application:
class C
def m
puts "barf"
end
end

In my module file:
module M
def self.included(mod)
mod.module_eval <<-EOF
def m
puts "c001c0de"
end
EOF
end
end

In the rake file:
C:send:)include, M)

Now I REALLY don't like module_eval(string). Is there a preferred
method to achieve this result?

module M
def self.included target
target.send :remove_method :m
end
def m; 42 end
end

Do you like this better?
You need rescue code in case m is not defined in C BTW

Cheers
Robert
 
B

blogger

Ahh, much better. I had missed remove_method. In my case, there is
no possibility of the method not being defined, but if there were, a
rescue nil would do nicely.
 

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

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top