coderrr

November 22, 2008

Super simple callbacks in Ruby

Filed under: ruby — Tags: — coderrr @ 8:22 pm

I was writing some tests and had a need for a simple callback mechanism. Here’s what I came up with:


class Server
  def on_disconnect(&block)
    if block
      @on_disconnect = block
    elsif @on_disconnect
      @on_disconnect.call
    end
  end
end

So now I can use the same method to create and call callbacks:


my_server.on_disconnect do
  puts 'we got disconnected!'
end

# ...

class Server
  ...
  rescue DisconnectError
    on_disconnect
    ...

Very simple and to the point and only a few lines of code. So maybe think of that next time you need a callback mechanism before you go looking for a bigger lib.

If you have a lot of callbacks you could use this:


module Callbacks
  def callback(*names)
    names.each do |name|
      class_eval <<-EOF
        def #{name}(*args, &block)
          if block
            @#{name} = block
          elsif @#{name}
            @#{name}.call(*args)
          end
        end
      EOF
    end
  end
end

And then you don’t need to write a method for every callback, you can just do:


class Server
  extend Callbacks

  callback :on_disconnect
end

# or to get it in all classes
class Module
  include Callbacks
end

3 Comments »

  1. Did you mean:

    def on_disconnect(&block)

    ???

    Comment by Reg Braithwaite — November 22, 2008 @ 11:52 pm

  2. yea. what a lame typo :/

    thanks man

    Comment by coderrr — November 23, 2008 @ 12:59 am

  3. Nice, I do something similar myself, but I hadn’t thought of writing a generator method like that, good job.

    Comment by Stefan Nuxoll — November 23, 2008 @ 9:22 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.