benjohn
3/21/2006 9:23:00 AM
This morning, I asked about using aliases and wrote:
*snip*
> I'd like to use a mechanism like this to enable me to have a kind of
> hookable function in a class. As I said, the alias process would be
> encapsulated by waving my hands and working that out later, but
> probably making use of method_defined.
>
> The mechanism allows you to build up an event handler: you send an
> event to a class instance, and any receivers that are registered for
> that event (by having defined the method to pick it up) will get it.
> Example hookable methods for my system will be: is_being_setup,
> will_be_torn_down, has_recieved_message will_send_message.
>
> It's worth noting that the will_be methods should probably be
> executed in the reverse order from that in which they are defined!
>
> I'm pretty sure this is a good plan, but...
>
> Question: "Does this seem like a good plan?"
Well, I still think the idea in general is good, but I've really gone
off the interface I was proposing. I think it's going to be hard to
implement anyway, and it's a bit unexpected to def a method, but have
really odd behaviour happen for no obviously visible reason...
> Finally, as this doesn't work, can you see a nicer way to implement
> it? I think I could capture the function each time it gets defined,
> and put it in to class state, but it would need to be per class, I
> think, rather than just on in the base class. I've thought about
> several variations, but none of them seem to be very nice at all.
The train on the way here got me thinking of another way. I now think a
good approach is to add a module method "add_to_hook" that can be used
thus:
class Blah
include Hook
def this_should_happen_on_hook_start_up; end
def this_should_also_happen_on_hook_start_up; end
add_to_hool :start_up, :this_should_happen_on_hook_start_up,
:this_should_also_happen_on_hook_start_up
end
And also add instance methods to support:
Blah.new.call_hook( :start_up )
Blah.new.call_hook_backwards( :tear_down )
The methods call_hook and call_hook_backwards will look for hooks added
in the receiver's class, and also it's superclasses (I'm going to leave
out any included modules for now, but I think that would also be fine).
The methods to be called will be despatched to as "normal" using the
instance method send. This allows them to be overidden in the normal
way, which could be useful.
I've got some tests on my laptop, and the start of an implementation
(doesn't do any looking in the superclass yet); I'll post them up, but
can't do so from work because of security paranoia :)
Two further things though:
* I don't like the name "hook" much, because there are lots of hooks
in to a hookable, really. Which is verging on being decidedly HP
Lovecraft. But "event" and "snooper" just sound weak.
* TDD rocks!