Simple observers for your code
Ruby
Switch branches/tags
Latest commit 2ce461c Mar 20, 2012 @foca Build status badge [ci skip]
Permalink
Failed to load latest commit information.
lib Allow on/trigger as aliases for watch/fire Mar 20, 2012
spec
.gitignore
.travis.yml Add a .travis.yml Mar 20, 2012
CHANGES
Gemfile
LICENSE Documentation, Rakefile, gemspec Apr 22, 2009
README.rdoc Build status badge [ci skip] Mar 20, 2012
Rakefile
beacon.gemspec

README.rdoc

Beacon

Simple observers and notifiers for your code.

The library aims to provide the simplest implementation possible. You get beacons, which are always global and can be “lit up”. Whenever you light a beacon up, everyone watching will act as instructed.

Build
Status

How to use this?

Whenever you want to fire an event from your code, call Beacon.fire:

def do_something
  Beacon.fire(:before_doing_something)
  # do your thing
end

In order to register listeners for that event, call Beacon.watch:

Beacon.watch :before_doing_something do
  logger.info "I'm about to do something"
end

Each time you call watch with a given name, you register a different handler for that name. Each time you call fire all handlers for that event are run, in the order they were registered.

You can use on as an alias of watch, and trigger as an alias of fire, since those seem to be popular choices among event observing libraries.

Passing arguments

If you want to pass arguments to the watchers, just pass them along in Beacon.fire:

Beacon.fire(:an_event, "cuack", 3)

And you'll get them as arguments on the block that handles the message:

Beacon.watch :an_event do |object, index|
  # here object == "cuack", index == 3
end

Advanced handlers

Instead of blocks, Beacon.watch can receive any object that responds to call, so if you need any advanced logic in your handlers, you can declare them like this:

class MyHandler
  def call(foo, bar=0)
    puts foo.inspect, bar
  end
end

Beacon.watch :an_event, MyHandler.new

Isolated events

You can include Beacon into your objects to have isolated events on a per-object basis if you need that:

class MyObservable
  include Beacon
end

obj = MyObservable.new
obj.watch(:an_event) { |object, *args| puts *args }
obj.trigger(:an_event, "foo")

Installing with rubygems

gem install beacon

Contributing

Clone our git repo from git://github.com/foca/beacon.git. The preffered way to send a patch is to push to a clone of the repo on github but if you want to mail me a patch or point me to a diff I won't complain. Though I'll probably take more to apply it :)

Authors

Code written by foca, with the help and ideas of halorgium, and tizoc.

The code is licensed under an MIT license. Check the LICENSE file for details.