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

Issue

This Content is from Stack Overflow. Question asked by BugBreeder

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).



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?