From: Lloyd Zusman Date: 2002-08-10T03:56:48+09:00 Subject: Re: Getting the file name from a File::Stat object? GOTO Kentaro writes: > At Fri, 9 Aug 2002 23:24:41 +0900, > Lloyd Zusman wrote: >> For that purpose, I know I can always use a subclass, like this: >> >> [ ... etc. ... ] > > You can redefine File.stat as follows, however, I don't recommend this > because File::stat is not API for a file but just for a inode. For > example, File::stat can represent a file which has been deleted already. > > [ ... etc. ... ] I totally agree with you, in the general case for the use of File::Stat. However, I have a specific need for ANY of the valid filenames that refer to the inode in question. It doesn't matter which of the names I use, as long as it's ONE of them. I want to use that name in order to implement a "File::Stat#textfile?" method that returns true if the item in question is a file which contains non-binary data. In order to implement the "textfile?" method, I have to have a filename that I can pass to an "open" method call, as follows: class File def self.stat(arg) Stat.new(arg) end class Stat alias_method :__old_initialize, :initialize attr_reader :item def initialize(arg) @item = arg __old_initialize(arg) end # New method that returns "true" if the item is a file # that only contains text data (i.e., non-"binary" data). def textfile? begin open(@item) { |file| block = file.read(self.blksize < self.size ? self.blksize : self.size) return block.size == 0 || ((block.count("^ -~", "^\b\f\t\r\n") / block.size) < 0.3 && block.count("\x00") < 1) } rescue return false end end end end s = File.stat("/etc/fstab") t = File.stat("/bin/sh") p s.textfile? # outputs `true' p t.textfile? # outputs `false' -- Lloyd Zusman ljz@asfast.com