re-define class method

D

David Chelimsky

I've got the following:

module ClassMethods
def class_method
"Class method"
end
end

class Thing
extend ClassMethods
end

Thing.class_method
=> "Class method"

... and I want to change the behaviour of that method at runtime. I
tried this:

Thing.send:)define_method, :class_method, lambda{ "replaced" })

... but I still get this:

Thing.class_method
=> "Class method"

Am I close? What's the right way to do this?

Thanks,
David
 
D

David Chelimsky

I've got the following:

module ClassMethods
def class_method
"Class method"
end
end

class Thing
extend ClassMethods
end

Thing.class_method
=> "Class method"

... and I want to change the behaviour of that method at runtime. I
tried this:

Thing.send:)define_method, :class_method, lambda{ "replaced" })

... but I still get this:

Thing.class_method
=> "Class method"

Am I close? What's the right way to do this?


OK - I've discovered that I can do this:

Thing.class.send:)define_method, :eek:ther_method, lambda{ "other" })
Thing.other_method
=> "other"

and even redefine it:

Thing.class.send:)define_method, :eek:ther_method, lambda{ "other
redefined" })
Thing.other_method
=> "other redefined"

but if I try this:

Thing.class.send:)define_method, :class_method, lambda{ "replaced" })
Thing.class_method
=> "Class method"

So it looks like I can replace class methods that I define at
runtime, but not the ones that were defined at load-time. Is that
correct? Am I missing a step?

Thanks,
David
 
D

David Chelimsky

Well, I discovered the solution, thanks to our friend google, and got
a much better understanding of singleton classes (though the fog
hasn't completely dissipated). For anyone interested:

thing_singleton_class = class << Thing; self; end
thing_singleton_class.send:)define_method, :class_method, proc
{ "replaced" })

Thing.class_method
=> "replaced"

Cheers,
David
 
D

David Chelimsky

Don't forget that you can do this much more concisely (unless you have
a specific need to go the long way round):

def Thing.class_method
"replaced"
end

Thanks David. I definitely appreciate the conciseness of this, and
will use that when I know the type. The problem I'm working on
requires a solution to replacing singleton methods on arbitrary types
at runtime, so I think I have to stick w/ the more cryptic version.
Unless you have a different suggestion - I'm just getting my head
wrapped around metaprogramming and singleton classes, so all
suggestions are most welcome.

Thanks,
David
 

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,780
Messages
2,569,611
Members
45,274
Latest member
JessMcMast

Latest Threads

Top