All right. I give up. I have no idea, but maybe one of the hardcore coders has. I have been trying this to write an extension to ActiveRecord, so that I can have an active Record that has an uri field (it should transparently return URI objects when queried. So I did this:
There we go again. Ruby has some, err… “unique” features when to the scope of variables. It really starts out really harmless, though…
This is part one of two – this one is just to give you a bit of background for the next one. There’s not much surprising stuff there, so if you want to go for the stranger bits, just jump to the next installment.
As I expected, I missed some stuff in my last post about adding methods at runtime. One thing is that the idiom for adding class methods is “class < < self" rather than "class << Classname"
More importantly, if you define things like I did in my last post, you will not be able to use variables in the method definition. The things after "class << self" are executed in a different scope that doesn't inherit the variables from the surrounding code.
One of the things that seems to draw people to Ruby is the ability to create and change all things at metprogrammatically at runtime. This in turn allows users to create things like domain-specific languages and the like.
I’m possibly overusing these features at the moment, because it’s a cool new thing ™.
So, let’s see how to add methods at runtime. Since this is Ruby, there are multiple ways to do this, making things more confusing.
(See also the follow-up article)