I've never seen undef - or any thing else that allows you to undefine a method - in any other programming languages. Why is it needed in Ruby?
EDIT: I'm not arguing that there is anything wrong with this. I just don't understand the purpose of defining methods at runtime? What's the purpose of that? How is it used? I've never done this in C or Java.
-
I don't think that it is necessarily "needed" by anything, but if you can define new methods at run-time in a programming language it makes sense to me that you should be able to un-define a method at run-time. What other programming languages are you thinking of? Are they able to define new methods at run-time?
-
Defining methods, classes and objects at runtime is a very nice feature of Ruby. It allows you to extend classes (remember they are "open"). If you look at Rails, it has a
#find
method to find objects in a model but you can also usefind_by_user
; that method does not exist (so#method_missing
is called) but gets created at run-time.If you want to create a Domain Specific Language or DSL, using
#missing_method
can be useful.LDomagala : actually #method_missing isnt used by activercord when you call find_by_user. the method is defined on class init -
You can look at all of Rails for examples of defining methods at runtime (aka metaprogramming). By calling one method in your class definition, it can define a whole bunch of methods for all instances of that class...
-
Theres also the blank class pattern in ruby that needs the undef functionality.
the idea is to strip every method from your new class so that every call you make to it ends in #method_missing. that way you can implement a real proxy that just shuffles everything through. implementing the decorator pattern with this is around 10 lines of code, no matter how big your target class is.
If you want to see that idiom in action look at one of rubys mocking frameworks, they use it alot. Something like flexmock.
Another example is when you add functions dynamicly onto a class based on some condition. In a game you might add an #attack method onto the player object and then take it away when he´s paralyzed instead of doing it with a boolean flag. That way the calling class can check for the availabty of the method and not the flag. I´m not saying that this is a good idea, just that it´s made possible and there are far smarter people then me coming up with useful stuff to do with this:)
0 comments:
Post a Comment