Popping messages from Ruby Queue in a proper way

68 Views Asked by At

Here is my code to send messages from Queue:

def initialize
    @messages = Queue.new
end

def send_messages_from_queue
    while msg = @messages.pop(true)
        #Pushing data through websocket
    end
rescue ThreadError
    #raised if queue is empty
end

It works but has one drawback: if there are no channel subscribers the message is not being sent but still taken out of the Queue and therefore goes lost.

How to take last message from Queue but not delete it from there until it is sent?

I could expose the inner queue:

@messages.class.module_eval { attr_reader :que }

or

@messages.define_singleton_method(:first_message) do
   @que.first
end

but it is not the right way and also has it's own drawback:

when I take a message out of Queue in one thread using pop, it won't be available for other thread few milliseconds later, but when I use the custom first_message method, the message will be available for any other thread until I call pop.

0

There are 0 best solutions below