Forum: Ruby Question concerning ruby file access

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Stefan S. (Guest)
on 2008-10-30 02:15
(Received via mailing list)
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.
Sebastian H. (Guest)
on 2008-10-30 02:26
(Received via mailing list)
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
Peña, Botp (Guest)
on 2008-10-30 03:35
(Received via mailing list)
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..
Ken B. (Guest)
on 2008-10-30 03:40
(Received via mailing list)
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
This topic is locked and can not be replied to.