Skip to content

davybrion/EventPublisher

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

The EventPublisher module enables you to define multiple events in a class, and have objects subscribe to them with either a Method instance, or a block.  Subscribers can obviously also unsubscribe Method instances, though blocks can't be unsubscribed.

To install, simply type this:

gem install eventpublisher

Here's a simple example that illustrates the usage of the EventPublisher module:

class Publisher
	include EventPublisher
	event :first_event
	event :second_event
	
	def trigger_events
		trigger :first_event, "first event"
		trigger :second_event, "second event", "extra argument"
	end
end

class FirstSubscriber
	def initialize(publisher)
		@publisher = publisher
		@publisher.subscribe_all self
	end
	
	def stop_listening
		@publisher.unsubscribe_all self
	end
	
	def first_event_handler(args)
		puts "first_event_handler of FirstSubscriber received #{args}"
	end
	
	def second_event_handler(arg1, arg2)
		puts "second_event_handler of FirstSubscriber received arg1 = #{arg1} arg2 = #{arg2}"
	end
end

class SecondSubscriber
	def initialize(publisher)
		@publisher = publisher
		@publisher.subscribe :first_event, method(:first_handler)
		@publisher.subscribe(:second_event) { |arg1, arg2| puts "block from SecondSubscriber received: #{arg1} #{arg2}"}
	end
	
	def stop_listening
		@publisher.unsubscribe :first_event, method(:first_handler)
	end
	
	def first_handler(args)
		puts "first_handler of SecondSubscriber received #{args}"
	end
end


publisher = Publisher.new
first_subscriber = FirstSubscriber.new(publisher)
second_subscriber = SecondSubscriber.new(publisher)
puts "you should see 4 outputted strings when the events are triggered"
publisher.trigger_events
first_subscriber.stop_listening
second_subscriber.stop_listening
puts "you should still see 1 outputted string because the block is still subscribed, while the Method instances have been unsubscribed"
publisher.trigger_events

The output of running this code is the following:

you should see 4 outputted strings when the events are triggered
first_event_handler of FirstSubscriber received first event
first_handler of SecondSubscriber received first event
second_event_handler of FirstSubscriber received arg1 = second event arg2 = extra argument
block from SecondSubscriber received: second event extra argument
you should still see 1 outputted string because the block is still subscribed, while the Method instances have been unsubscribed
block from SecondSubscriber received: second event extra argument

About

EventPublisher module for Ruby

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages