Ruby class 设计 - 我应该在单独的文件中创建常量吗?

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

我是 Ruby 的新手,使用 Bunny 消费来自 RabbitMQ 的消息。

所以我的 class 目前大致是这样的:

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

我的问题是文件变得很长,所以我想以某种方式减少它。所以我想到的一件事是,将 initialize 中的那一长串加入队列移动到另一个文件中,因为它们是不变的。

但是正确的方法是什么,我应该创建一个模块,复制所有这些 joinQueue 行,然后在 goWork 中将它们作为常量引用,例如:QUEUEMAIN?

任何 ideas/suggestions 将不胜感激。

想了解好的设计吗?

谢谢。

这里还有更多你可以重构的东西,但基本上是的,你把提升移到了一个模块上,感谢@Amadan,你可以

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

另请参阅 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 以帮助记住正确的样式。