带有EventMachine模块的实例变量

时间:2015-11-24 06:46:52

标签: ruby eventmachine

我正在编写一个使用EventMachine来中继服务命令的应用程序。我想重新使用与服务的连接(不为每个新请求重新创建它)。该服务从模块方法启动,该模块提供给EventMachine。如何在事件机器方法中存储连接以便重复使用?

我拥有(简化):

require 'ruby-mpd'
module RB3Jay
  def self.start
    @mpd = MPD.new
    @mpd.connect
    EventMachine.run{ EventMachine.start_server '127.0.0.1', 7331, self }
  end
  def receive_data
    # I need to access @mpd here
  end
end

我到目前为止唯一的想法是@@class_variable,但我考虑这样的黑客的唯一原因是我不习惯EventMachine并且不知道更好的模式。如何重构我的代码以在请求期间使@mpd实例可用?

2 个答案:

答案 0 :(得分:2)

您可以继承EM::Connection而不是使用模块方法,并将mpd传递给EventMachine.start_server,这会将其传递给类“initialize方法”。

require 'ruby-mpd'
require 'eventmachine'

class RB3Jay < EM::Connection
  def initialize(mpd)
    @mpd = mpd
  end

  def receive_data
    # do stuff with @mpd
  end

  def self.start
    mpd = MPD.new
    mpd.connect

    EventMachine.run do
      EventMachine.start_server("127.0.0.1", 7331, RB3Jay, mpd)
    end
  end
end

RB3Jay.start

答案 1 :(得分:1)

我相信这可能是单身人士课程的机会。

require 'ruby-mpd'
require 'singleton'

class Mdp
  include Singleton
  attr_reader :mpd

  def start_mpd
    @mpd = MPD.new
    @mpd.connect
  end
end

module RB3Jay
  def self.start
    Mdp.instance.start_mdp
    EventMachine.run{ EventMachine.start_server '127.0.0.1', 7331, self }
  end
end

class Klass
  extend RB3Jay

  def receive_data
    Mdp.instance.mpd
  end
end

此代码段假定在创建Klass.start的实例之前已调用Klass

相关问题