-->

Sharing instance variables between classes ruby

2020-07-23 12:19发布

问题:

I know that this question has been answered before, but I can't seem to make any of the solutions work

I'm making a ruby wrapper for an API that I need to call. The Interface class does all of the session handling and actual calling of the api, but I want to build helper classes for the functions that I will be performing most frequently. The problem I am having is that I need a way of maintaining one instance of the Interface class across multiple helper classes.

Here's the code I have so far

require_relative 'interface'

module Api_Helper
  attr_accessor :xmlmc
    #get a new instance of the interface, This should be the only instance used.
    #I don't know if this needs to go in its own module
  def initialize server, port = '5015'
    @xmlmc = Xmlmc::Interface.new server, port
  end
end

module Xmlmc
  class API
    include Api_Helper
    module Session
        #session helpers use invoke method to send calls to the api via the interface class
        def invoke service, operation, parameters
            Xmlmc::API.xmlmc.invoke service, operation, parameters
        end 
    end
    module Data
        #data helpers use invoke method to send calls to the api via the interface class
        def invoke service, operation, parameters
            Xmlmc::API.xmlmc.invoke service, operation, parameters
        end 
    end

    def session
      #extend the session module into its own class
      _session = Object.new
      _session.extend Session
      _session
    end

    def data
      #extend the data helpers into its own class
      _data = Object.new
      _data.extend Data
      _data
    end
  end
end

I want to be able to use my code like this.

api = Xmlmc::API.new 'localhost', '2000'
@session = api.session
@session.logon 'username', 'password' 
@data = api.data
@data.query = 'select * from table' #requires a session first.

The problem that I am having is that the Interface class handles the session token which changes from call to call. I want to be able to have my code cleanly divided into sections, like session and data while using only one instance of the interface class.

I don't want to have these methods return anything more than the API return values. That is I don't want to manually pass around an instance of the interface class or session variables etc. Is this possible?