我正在编写一个应用程序,它使用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
实例在请求期间可用?
发布于 2015-11-24 13:01:40
您可以继承EM::Connection
并通过EventMachine.start_server
传递mpd
,而不是使用模块方法,后者将把它传递给类的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
发布于 2015-11-24 12:35:33
我相信这可能是一个单身学生的机会。
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
实例之前被调用。
https://stackoverflow.com/questions/33887113
复制相似问题