Skip to content

Instantly share code, notes, and snippets.

@serradura
Created May 11, 2022 15:18
Show Gist options
  • Save serradura/b5dd8e8605a51f4e59c7a9b86b276c5a to your computer and use it in GitHub Desktop.
Save serradura/b5dd8e8605a51f4e59c7a9b86b276c5a to your computer and use it in GitHub Desktop.
Implementação do pub/sub na mão equivalente a gem Wisper
module Susurro
def subscribe(handler)
subscribers << {name: nil, handler: handler}
self
end
def on(event_name, &handler)
subscribers << {name: event_name, handler: handler}
self
end
def publish(event_name, data)
subscribers.each do |event|
handler = event[:handler]
if event[:name] == event_name
handler.call(data)
elsif handler.respond_to?(event_name)
handler.public_send(event_name, data)
end
end
end
alias_method :broadcast, :publish
private
def subscribers
@subscribers ||= []
end
end
class Person
include Susurro
def name=(name)
publish(:name_changed, {from: @name, to: name})
@name = name
end
def name
@name
end
end
class NameChangeListener
def name_changed(data)
puts '======='
puts "from: #{data[:from]}"
puts "to: #{data[:to]}"
puts '======='
end
end
person = Person.new
person.on(:name_changed) do |data|
p data
end
person.name = 'Rodrigo'
person.name = 'Serradura'
person.subscribe(NameChangeListener.new)
person.name = 'Rodrigo Serradura'
@asbieajahwis
Copy link

Verify Github on Galxe. gid:awHToTWtodFK4ovfcYPnfh

@asbieajahwis
Copy link

Verify Github on Galxe. gid:awHToTWtodFK4ovfcYPnfh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment