Question concerning ruby file access


#1

Question concerning ruby file access from a novice:

I have seen following code fragment from

http://www.rubycentral.com/pickaxe/tut_io.html

File.open(“testfile”, “r”) do |aFile|

… process the file

end

Advantage of this notation is that file is automatically closed when do
loop terminates – maybe by an exception with Process.exit.

But how do I test in this notation that the file with name “testfile”
really exits (and opening was successful). In an multi-tasking
environment another process may delete the file just before this
statement is executed.

Or in other words: I want to print a text like “File with filename
“testfile” does not exist” when opening failed.

Best regards

Stefan S.


#2

Stefan S. wrote:

But how do I test in this notation that the file with name “testfile”
really exits (and opening was successful). In an multi-tasking
environment another process may delete the file just before this
statement is executed.

If you want to completely avoid race conditions, you don’t check - you
just do
and then recover from eventual errors (i.e. you rescue the exception).

HTH,
Sebastian


#3

From: Stefan S. [mailto:removed_email_address@domain.invalid]

Or in other words: I want to print a text like "File

with filename “testfile” does not exist" when opening failed.

i usually think it like db’s logical unit of work or transaction. i just
wrap it w ruby’s begin/end and a rescue check as mentioned by sebastian.

something like eg

begin

  • File.open(“test.rbx”) do |f|
  • end

rescue =>e
p e.message
end
“No such file or directory - test.rbx”
=> nil

note, you can have more rescues and finetune them. you can also make
your own exceptions… just continue reading on the pickaxe…


#4

On Thu, 30 Oct 2008 00:14:57 +0000, Stefan S. wrote:

loop terminates – maybe by an exception with Process.exit.

Stefan S.

begin
File.open(“testfile”) do |aFile|

end
rescue IOError => e
#handle error
end