From: Robert Klemme Date: 2005-08-31T17:26:23+09:00 Subject: Re: More elegant replacement for global variables Michael wrote: > I'm playing around with a ruby app using XML-RPC. Currently I'm using > global variables so I can create multiple objects without having to > log > in for each and every object. > > class Base > def initialize(user, pass) > $user, $pass = user, pass > end > > def login() > $client = XMLRPC::Client.new(...) > $sessionid = $client.call("xmlrpc.method", $user, $pass) > return $sessionid > end > end > > Derived classes look like this: > > class Object1 < Base > def initialize() > if not $sessionid then self.login end > end > end > > This way I can log in once with the first object created without > having > to log in each time. However, this seems inelegant to me. Is there a > more elegant, or just more rubyish, way of doing this? Also, I'd have > potential problems if I wanted to log on as multiple users. > > Would it make more sense just to pass around an instance of the Base > object: > > class Object2 > def initialize(xmlrpc_client) > if not xmlrpc_client.sessionid then xmlrpc_client.login > end > > def call_xmlrpc_method(method, params) > results = xmlrpc_client.call(method, params) > return results > end > end > > xmlrpc_client = Base.new > o2 = Object2.new(xmlrpc_client) > > Pro: no global variables. Con: coupling between Object2 and Base > classes. --Michael Although your scenario is not fully clear to me, I'd have a session instance that stores all session related information. Also I would not have your classes (Object1) inherit the session class but instead pass it around. Kind regards robert