1

I'm new to Ruby, using Bunny to consume messages from RabbitMQ.

So my class currently looks roughly like this:

class Consumer

  include Validator

  def initialize
    #Start a RabbitMQ session
    @rdSession = Session.new

    @queueMain = rdSession.joinQueue('QueueMain')
    @queueLittle = rdSession.joinQueue('QueueLittle')
    ...
    @queueTen = rdSession.joinQueue('QueueTen')

    goWork
  end

  def goWork
     @queueMain.subscribe(:manual_ack => true) do |delivery_info, properties, payload|
        goDoSomethingElse(payload)
      end
     ....
     @queueTen.subscribe(:manual_ack => true) do |delivery_info, properties, payload|
        goDoAnotherPiece(payload)
      end
  end

My question is the file is becoming quite long so I want to reduce it somehow. So one thing I thought of is as those moving that long list of joining queues in initialize into another file as they are constant.

However what is the correct way to do this, should I create a module, copy across all those joinQueue lines, then refer to them in goWork as constants like: QUEUEMAIN?

Any ideas/suggestions would be appreciated.

Trying to understand good design for this?

Thanks.

userMod2
  • 8,312
  • 13
  • 63
  • 115

1 Answers1

1

There's more you can refactor here but basically yes you move the lifting to a module and thanks to @Amadan, you can

module GoWork
  def goWork
    @queues[:QueMain].subscribe(:manual_ack => true) do |delivery_info, properties, payload|
      goDoSomethingElse(payload)
    end
    @queues[:QueTen].subscribe(:manual_ack => true) do |delivery_info, properties, payload|
      goDoAnotherPiece(payload)
    end
  end
end

class Consumer

  include Validator
  include GoWork

  QUEUE_NAMES = %w(QueueMain QueueLittle QueueTen) 

  def initialize
    #Start a RabbitMQ session
    @rdSession = Session.new
    @queues = QUEUE_NAMES.map { |name| [name.to_sym, rdSession.joinQueue(name)] }.to_h

    goWork
  end
end

Also see ruby style guide it is recommended to user snake_case for all method and variable names and to use CamelCase for class and module definitions, but I didn't do that as that was not your question. It is also recommend to use Rubocop to help keep proper style in mind.

lacostenycoder
  • 10,623
  • 4
  • 31
  • 48
  • Thanks - so I was actually thinking moving the `@queueMain = rdSession.joinQueue('QueueMain')` bits into a module. Any other refactor suggestions you have? – userMod2 Oct 29 '18 at 01:07
  • 2
    Regarding "that long list of joining queues", I'd probably have `QUEUE_NAMES = %w(QueueMain QueueLittle QueueTen)` and `@queues = QUEUE_NAMES.map { |name| [name.to_sym, rdSession.joinQueue(name) }` - no need for each of them to get their own instance variable. This renames `@queueMain` to `@queues[:QueueMain]`. – Amadan Oct 29 '18 at 01:14