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


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
    def publish(event, *payload)
      @subscribers ||= []
      @subscribers.each do |subscriber|
        subscriber.public_send(event.to_sym, *payload) if subscriber.respond_to?(event)

class Checkout
    include MyPublisher

checkout =
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

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 |data| block/listener? (I also put a comment to show where I am talking about).


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?