Ruby Event Handlers: Improved Object Model

I’ve been cleaning up the implementation of Unobservable so that it better adheres to Ruby’s object model.  As a result, the following features are now available:

Singleton Events

It is possible to define singleton events on an object now.  This could be useful if you have a “one off” object and don’t feel like defining an entire class just for the one object:

require 'unobservable'

x =

# Add support for events
x.extend Unobservable::Support

# Define a singleton event
x.define_singleton_event :foo

# Now we can treat the singleton event
# just like a regular event { puts "foo" }

Easier Event Querying

It’s much easier to figure out which Events were explicitly defined by a Class / Module, and which were inherited by other means:

require 'unobservable'

class Foo
  include Unobservable::Support
  attr_event :foo

class Bar < Foo
  attr_event :bar

module Bloop
  include Unobservable::Support
  attr_event :bloop

# Show all instance events
Bar.instance_events        # [:bar, :foo]

# Show only the instance events that were
# defined by Bar.
Bar.instance_events(false) # [:bar]

# Let's create an instance of Bar and
# add a singleton event while we're at it.
x =
x.define_singleton_event :quux
x.extend Bloop

# Show all events on x                   # [:quux, :bloop, :bar, :foo]

# Show only the events that were
# defined explicitly by x            # [:quux]

# Show all singleton events
x.singleton_events         # [:bloop, :quux]

# Show only singleton events that were
# defined explicitly by x
x.singleton_events(false)  # [:quux]

Method Creation is Optional

Unobservable no longer forces you to create a Method for each Event:

require 'unobservable'

class Foo
  include Unobservable::Support
  attr_event :foo, :create_method => false

x =

# The #foo method is not defined...
x.respond_to?(:foo)     # false

# ... but the :foo event still exists.
x.event(:foo).register { puts "bar" }

Closing Remarks

Unobservable is getting closer to an official “1.0.0″ release.  Some tasks that still remain:

  • Allowing developers to un-define events
  • Adding support for “Event Missing”
  • Adding basic query methods (ex:  “event_defined?” )

You can find more information about the library using the links below:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>