How to consume data from a pub/sub pattern in ruby?

Viewed 21

I am new to Ruby and have been following a couple of tutorials to learn more about it.

Here's the baseline code. I have a Publisher and a class, Checkout, that includes this Publisher.

module MyPublisher
    def subscribe(subscribers)
      @subscribers += subscribers
    end
  
    def publish(event, *payload)
      @subscribers ||= []
      @subscribers.each do |subscriber|
        subscriber.public_send(event.to_sym, *payload) if subscriber.respond_to?(event)
      end
    end
end

class Checkout
    include MyPublisher
end 

checkout = Checkout.new
items = []

checkout.subscribe "event-item-added" do |data|
    # How can I get here inside this listener? So that "item << data" is executed?
    puts "checkout received an item!"
    items << data
end

queue.publish "event-item-added", 52
queue.publish "event-item-added", 90
queue.publish "event-item-added", 16

My question is: how to get the data that is published inside the ...do |data| block/listener? (I also put a comment to show where I am talking about).

0 Answers
Related