Editing Topic: RCR210 Project: RCR | RCRchive home

RCR 210: event keyword for ruby

submitted by sanatg on Sun Feb 08 2004 10:19:50 PM -0800

Status: withdrawn


Abstract

Ruby currently lacks an event keyword. It is possible to implement event handlers by defining method pointers and attaching blocks at runtime. However, an event keyword would reduce the typing required when defining events.

Problem

The following code block implements an Authenticator class with 2 events - on_authenticate and on_failure. The Consumer class attaches method blocks to these event handlers at runtime.
class Authenticator
        #event
        def on_authenticate(&on_authenticate)
                @on_authenticate = on_authenticate
        end

        #event
        def on_failure(&on_failure)
                @on_failure = on_failure
        end

        #constructor
        def initialize
                on_authenticate {}
                on_failure {}
        end
        
        def authenticate(username, password)
                if username == 'john' and password == 'doe'
                        @on_authenticate.call
                else
                        @on_failure.call
                end     
        end
end

class Consumer
        #event handler
        def on_authenticate
                puts 'Successfully authenticated'
        end
        
        def on_failure
                puts 'Authentication failed'
        end
        
        def run
                auth = Authenticator.new
                
                #attach event handlers
                auth.on_authenticate {on_authenticate}
                auth.on_failure {on_failure}
                
                auth.authenticate('john', 'doe') #succeeds
                auth.authenticate('jim', 'smith') #fails
        end
end

Consumer.new.run
The definition of Authenticator above requires defining 2 attributes that point to a method and initializing those attributes with empty blocks.

Proposal

An event keyword with some of the plumbing handled by the runtime would solve this problem. For example, the above code for Authenticator would look something like -
class Authenticator
        #events
        event on_authenticate, on_failure

        def authenticate(username, password)
                if username == 'john' and password == 'doe'
                        @on_authenticate.call
                else
                        @on_failure.call
                end     
        end
end

Analysis

The addition of the event keyword would eliminate the need to define method pointers and assigning them to attributes. This would be handled by the Ruby runtime. Also the need to assign empty blocks in the constructor would not be required, so attaching an event handler in the consuming class is not mandatory.


Back to RCRchive.


RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog