Provides Publish/Subscribe pattern.
To install it, add the gem to your Gemfile:
gem 'spine-hub'
Then run bundle
. If you're not using Bundler, just gem install spine-hub
.
class Service
include Spine::Hub::Publisher
def action
publish(:action_executing)
# ...
publish(:action_executed, 'OK')
end
end
class Listener
include Spine::Hub::Subscriber
def on_action_executing
puts 'Executing action'
end
end
service = Service.new
service.subscribe(Listener.new)
service.on(:action_executed) do |status|
puts "Action executed: #{ status }"
end
service.action
There is also Spine::Hub::Repeater
, which repeats subscribed events. If you
need to get more control over subscriber event handling, implement notify
method:
class MySubscriber
def notify(event, *arguments)
# Handle events
end
end
When global subscribers are needed, extend your publisher with
Spine::Hub::Subcriptions::Global
module. It also works with Repeater
module.
class Service
include Spine::Hub::Publisher
include Spine::Hub::Subscriptions::Global
def action
# ...
end
end
For registering to global scope:
Spine::Hub.subscribe(MySubscriber.new)
Spine::Hub.on(:my_event) do |argument|
# ...
end