Joel VanderWerf
3/31/2006 9:55:00 PM
PrimaryKey wrote:
>> How would you use static constructors/destructors? Perhaps we can show
>> you Ruby equivalents.
>>
>> --
>> -- Jim Weirich
>
> Please consider the following (pseudo) C# example:
>
> public class AS400Server
> {
> static AS400 server;
>
> static AS400Server()
> {
> server = new AS400Connection("SERVERNAME");
> }
>
> static ~AS400Server() // This is not real C#
> {
> server.disconnect();
> }
>
> static int GetServer()
> {
> return server;
> }
> }
I would ask first: does having one class per connection ("SERVERAME")
scale well? what if you need two servers...? This question isn't really
off topic, because once you accept this possibility, it becomes very
natural in ruby to do this:
class AS400Server
def initialize(serv_name)
@serv_name = serv_name
end
def connect
# do something to connect to the server
yield self
ensure
# do something to disconnet
end
end
Then in your main code you might have:
def run_my_app
AS400Server.new("SERVERNAME").connect do |serv|
# do something with serv
end
end
or
THE_SERVER = AS400Server.new("SERVERNAME")
def run_my_app
THE_SERVER.connect do
# do something with THE_SERVER
end
end
Unless you exit with Kernel#exit! or the process is killed in a way that
ruby cannot catch (e.g., SIGKILL), the ensure clause will close the
server connection first. (Anyway, in the case of SIGKILL, a static
destructor would not be called either, right? Or can C# do that?)
(You can even roll the #connect method into initialize, if you want.
Passing the server object from yeild isn't really necessary, but you may
need to reference it in the block.)
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407