Search code examples
rubyeventmachine

Instance variable with EventMachine module


I'm writing an app that uses EventMachine to relay commands from a service. I want to re-use the connection to the service (not re-create it for each new request). The service is started from a module method, and that module is supplied to EventMachine. How can I store the connection for re-use in event machine methods?

What I have (simplified):

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

My only thought so far has been a @@class_variable, but the only reason I'm considering a hack like this is that I'm not used to EventMachine and do not know a better pattern. How can I refactor my code to make the @mpd instance available during requests?


Solution

  • Instead of using the module method, you can inherit EM::Connection and pass mpd through EventMachine.start_server, which will pass it onto the class' initialize method.

    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