Joel VanderWerf
2/3/2009 9:35:00 PM
David Stanford wrote:
>> Use exceptions?
>>
>> begin
>> File.delete(lf)
>> rescue Errno::ENOENT
>> File.delete(@lf)
>> end
>
> Thanks Joel. Forgive me, I'm just learning Ruby/scripting/programming. I
> believe I understand your example, but (as far as I can tell) it doesn't
> really accomplish my goal, and seems to have the same functionality of
> my first (longer) example.
>
> Please let me know if I've missed something. :)
>
> In any case, I think I found a (seemingly) obvious solution to my
> question:
>
> @lockfile = some_other_lockfile
>
> def self.unlock(lockfile)
> File.exist?(lockfile) ? File.delete(lockfile) : File.delete(@lockfile)
> end
With exceptions, you are saying "try to delete lf; if that fails
(because the file doesn't exist) then try to delete @lf". Other failures
(e.g., lf permissions are wrong, or @lf doesn't exist) are reported
normally as exceptions.
One advantage to doing it this way is that the delete is an atomic
operation. With
File.exist?(lockfile) ? File.delete(lockfile) : File.delete(@lockfile)
there is the possiblity that #exist? will return true, but in the brief
time before #delete is called, some other process deletes the file.
Btw, it looks to me like your #unlock implementation above is the same
as your first implementation. The ? : construct is really the same as
if...else, just more compact.
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407