Ruby on Rails: Cleverness! Evil!
I was reading one of my Ruby on Rails texts (Agile Web Development with Rails, 2nd Ed.), and I came upon something that made me laugh out loud:
(code snippet):
user = self.find_by_name(name)This code uses a clever little Active Record trick. You see that the first line of the method calls find_by_name. But we don’t define a method with that name. However, [the base class, ] ActiveRecord notices the call to an undefined method and spots that it starts with the string find_by and ends with the name of a column. It then dynamically constructs a finder method for us, adding it to our class…
That’s…so cool! And evil! Not only does it dynamically notice that you want the method, and dynamically interrogate the database schema to see that it makes sense as a column name, and do what you want, but it also dynamically alters the class so that it will now have the method. The second time you call the method, it will just be called directly.
We could certainly do the cool part in Java, where the many names are recognized dynamically. We couldn’t do the evil part, where the actual class is altered at runtime, but I don’t think that dynamic delegation is supposed to be that slow. There is the query to the schema, though…hm.
To me, altering the class at runtime feels like having a superpower, something that, if you really need it, could seriously help you out of a jam, but which you constantly have to tell yourself to only use when you can’t help it.
But it is cool. And evil.
Post a Comment