Created
January 5, 2018 12:15
-
-
Save solnic/4004be6316ea72adae33ffd098016e3b to your computer and use it in GitHub Desktop.
A simple dry-monitor example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'dry/monitor/notifications' | |
module MyApp | |
def self.notifications | |
@__notifications__ ||= Dry::Monitor::Notifications.new(:my_app) | |
end | |
notifications.register_event("users.created") | |
class Logger | |
def on_users_created(user:, object:, time:) | |
puts "user #{user} created by #{object} in #{time}ms" | |
end | |
end | |
class CreateUser | |
attr_reader :notifications | |
def initialize(notifications) | |
@notifications = notifications | |
end | |
def call(user) | |
notifications.instrument("users.created", object: self, user: user) do | |
# do your thing | |
sleep 1 | |
user | |
end | |
end | |
end | |
end | |
# subscribe an object where its methods are treated as event listeners | |
MyApp.notifications.subscribe(MyApp::Logger.new) | |
# subscribe arbitrary code as an event listener | |
MyApp.notifications.subscribe("users.created") do |event| | |
puts "EVENT: #{event.id}" | |
puts "PAYLOAD: #{event.payload.inspect}" | |
end | |
create_user = MyApp::CreateUser.new(MyApp.notifications) | |
create_user.call(name: "Jane") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
user {:name=>"Jane"} created by #<MyApp::CreateUser:0x007fa61618d1c0> in 1005.25ms | |
EVENT: users.created | |
PAYLOAD: {:object=>#<MyApp::CreateUser:0x007fa61618d1c0 @notifications=#<Dry::Monitor::Notifications:0x007fa6158651d8 @id=:my_app, @clock=#<Dry::Monitor::Clock:0x007fa6158779a0>, @__bus__=#<Dry::Events::Bus:0x007fa61585ea40 @listeners=#<Concurrent::Map:0x007fa61585f3f0 entries=1 default_proc=#<Proc:0x007fa61606bb98@/Users/solnic/Workspace/dry-rb/dry-events/lib/dry/events/constants.rb:8>>, @events=#<Concurrent::Map:0x007fa61585ff80 entries=1 default_proc=nil>>>>, :user=>{:name=>"Jane"}, :time=>1005.25} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment