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

时间:2018-10-29 00:46:23

标签: ruby bunny

我是Ruby的新手,使用Bunny来吸收RabbitMQ的消息。

所以我的课目前看起来像这样:

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

任何想法/建议将不胜感激。

试图了解好的设计吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以在此处重构更多的内容,但是基本上可以,您可以将举升转移到模块上,感谢@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,建议用户snake_case获取所有方法和变量名称,并建议将CamelCase用于类和模块定义,但是我没有这样做,不是你的问题。还建议使用Rubocop帮助记住适当的样式。