Search code examples
rubybunny

Ruby class design - should I create constants in a seperate file?


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.


Solution

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