3 ms·
Ah, is this the "monkey patching" I've heard (so many bad things) about? Or something closer to Objective C's protocols and Java's interfaces?
by edw 16y ago
Ah, is this the "monkey patching" I've heard (so many bad things) about? Or something closer to Objective C's protocols and Java's interfaces?
- SlyShy 16y agoMan, who down votes someone for asking a genuine question? This isn't monkey patching. Ruby's classes are open (they can be modified on the fly), so you can monkey patch modules with new functionality. In a language like C, if you wanted to extend a library, you might modify it and recompile. Ruby's module_eval and class_eval are meta-programming tools that let you programmatically add methods to classes (and lots of other stuff), this can be combined with monkey patching, if you so desire.
- josevalim 16y agoNo, no. Monkey patching is what you can do when you have open classes. For instance, in Ruby, I can reopen the Array class and add new behavior or change existent methods. This is obviously bad idea if you are changing native behavior, but it is also what allows Ruby on Rails to extend the Integer class to make working with time expressions quite easy, as allowing the following expression: "3.days.ago". I still haven't decided if Elixir will have open class or if I will add refinements or classboxes. On other hand, module_eval is what allows frameworks like Rails to dynamically add code to a class, so you can do stuff like: class Post has_many :comments end And it will define a comments method and others, that allows you to easily manipulate the Post-Comment association.