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.
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
Back to RCRchive.
RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog