Class: Smith::Commands::Pop

Inherits:
Smith::CommandBase show all
Defined in:
lib/smith/commands/smithctl/pop.rb

Instance Attribute Summary

Attributes inherited from Smith::CommandBase

#options, #target

Instance Method Summary collapse

Methods inherited from Smith::CommandBase

#banner, #format_help, #initialize, #parse_options

Methods included from Logger

included

Constructor Details

This class inherits a constructor from Smith::CommandBase

Instance Method Details

#executeObject



7
8
9
# File 'lib/smith/commands/smithctl/pop.rb', line 7

def execute
  pop
end

#popObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/smith/commands/smithctl/pop.rb', line 11

def pop
  case target.size
  when 0
    "No queue specified. Please specify a queue."
  when 1

    queue = target.first

    Messaging::Queue.number_of_messages(queue) do |queue_length|

      # Number of messages on the queue.
      number_to_remove = (options[:number] > queue_length) ? queue_length : options[:number]

      Messaging::Receiver.new(queue, :auto_ack => false, :prefetch => number_to_remove, :passive => true) do |receiver|

        receiver.on_error do |ch,channel_close|
          case channel_close.reply_code
          when 404
            responder.succeed("Queue does not exist: #{queue}")
          else
            responder.succeed("Unknown error: #{channel_close.reply_text}")
          end
        end

        worker = proc do |acc, n, iter|
          receiver.pop do |payload,r|
            if payload
              acc[:result] << print_message(payload) if options[:print]
              acc[:count] += 1

              if n == number_to_remove - 1
                if options[:remove]
                  r.ack(true)
                else
                  r.reject(:requeue => true)
                end
              end
            end
            iter.return(acc)
          end
        end

        finished = proc do |acc|
          logger.debug { "Removing #{acc[:count]} message from #{receiver.queue_name}" }
          responder.succeed(acc[:result].join("\n"))
        end

        EM::Iterator.new(0...number_to_remove).inject({:count => 0, :result => [], :ack => nil}, worker, finished)
      end
    end
  else
    "You can only specify one queue at a time"
  end
end