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 = Object.new

# 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
x.foo.register { puts "foo" }
x.foo.call

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
end

class Bar < Foo
  attr_event :bar
end

module Bloop
  include Unobservable::Support
  attr_event :bloop
end

# 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 = Bar.new
x.define_singleton_event :quux
x.extend Bloop

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

# Show only the events that were
# defined explicitly by x
x.events(false)            # [: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
end

x = Foo.new

# 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>