Reputation: 3782
I'm new to ruby file IO. I have a function that takes a File
parameter, and I need to make sure that the file is in read-only mode.
def myfunction(file)
raise ArgumentError.new() unless file.kind_of?(File)
#Assert that file is in read-only mode
end
Any help would be appreciated!
Upvotes: 1
Views: 714
Reputation: 24
You can use file.readable?
, which returns true or false.
Please check this link.
Upvotes: 0
Reputation: 1279
So all you need is 'make sure make sure that the file is in read-only mode', why not just set it as readonly with FileUtils.chmod.
Or if actually you just want to test if it is readonly, use File.writeable
?
Upvotes: 2
Reputation: 4657
If you don't need to raise an error, you can use reopen
, I think something like:
file = file.reopen(file.path, "r")
I can't find a way to otherwise verify that there isn't a write stream, but here's a bit of a hack that will work. Although I don't like exception throwing being used in the expected path, you could use close_write
:
begin
file.close_write
# you could actually raise an exception here if you want
# since getting here means the file was originally opened for writing
rescue IOError
# This error will be raised if the file was not opened for
# writing, so this is actually the path we want
end
Upvotes: 2