----- Original Message ----- 
From: "Patrick May" <patrick-may / monmouth.com>
Newsgroups: comp.lang.ruby
To: "ruby-talk ML" <ruby-talk / ruby-lang.org>
Sent: Friday, August 30, 2002 6:36 PM
Subject: Re: How to write scripts with plug-in support [long]


> > I think I have an extremely simple but useful callback-mechanism,
> > I send it in an attachment.
> 
> I did not recieve this attachment.  Is this posted somewhere?
> 
> Looks interesting,
> 
> ~ Patrick

Here it is... pasted below.

Hal


#!/usr/bin/env ruby

class CallbackStack
  def initialize
    @table = {}
    @id    = 0
  end
  
  # You should give your callback a unique name (id) 
  # if you want to delete or overwrite it!
  # The stack returns a unique id if you don't specify any (nil).
  def add(proc=nil,id=nil)
    if id 
      if proc
        @table[id] = proc
        id
      else
        @table.delete(id)
      end
    else
      if !proc
        @table.clear
        nil
      else
        @id+=1 while @table[@id]
        @table[@id] = proc
        @id
      end
    end
  end
  
  def call(*x)
    for id,proc in @table
      proc.call(*x) 
    end
  end
  
  def register(&block)
    add(block)
  end
  
  # call it now + register
  def always(&block)
    block.call(self)
    add(block)
  end
end