Preferred way to overwrite an object method?

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?

On Dec 6, 2007 7:00 PM, blogger [email protected] wrote:

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

http://ruby-smalltalk.blogspot.com/


All truth passes through three stages. First, it is ridiculed. Second,
it is violently opposed. Third, it is accepted as being self-evident.
Schopenhauer (attr.)

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs