Ruby - Ensure Syslog Gets Closed
Question
Is it absolutely critical that I always close Syslog when I'm done using it? Is there a huge negative impact from not doing so?
If it turns out that I definitely need to, what's a good way to do it? I'm opening Syslog in my class constructor and I don't see a way to do class destructors in Ruby, and currently have something resembling this:
class Foo
def initialize
@@log = Syslog.open("foo")
end
end
I don't immediately see the place where the Syslog.close
call should be, but what do you recommend?
Solution
The open method accepts a block. Do something like this:
class Foo
def do_something
Syslog.open do
# work with the syslog here
end
end
end
OTHER TIPS
It looks like you're opening it as a class variable... so the proper way would be to do...
class Foo
def initialize
@@log = Syslog.open("foo")
end
def Foo.finalize(id)
@@log.close if @@log
end
end
Though this is not necesssarily predictable or supported. It's the way to do it if you're going to keep the code the way you do.