Politics, Programming and Possibilities
24 Jul
There is likely a way to do what I’m about to blog about, but I thought this might be useful in case there isn’t. Basically, I want a File object, but without the necessity of it actually being a file on the filesystem. For example, I’d kind of like to call "/tmp/myfile.txt".dirname and get "/tmp" back.
Ruby’s File class does not allow the following, unless /tmp/myfile.txt actually exists:
f = File.new("/tmp/myfile.txt")
And what’s worse (imo), you can’t do this once you have the file handle:
f.dirname
But it does allow this:
File.dirname("/tmp/myfile.txt")
When you have a lot of this kind of thing going on (getting dirname, basename, extname, etc.) it gets tiresome to type “File” all over the place. What we really need is a Filename object. And it should proxy methods to the File.* class methods. Here it is:
##
# Simple class that makes File.* class methods available on a
# Filename object
#
# doctest: Can call File's class methods on a Filename object
# >> Filename.new ("/tmp/myfile.png").dirname
# => "/tmp"
#
# doctest: Can create a Filename from another Filename object
# >> path = "/tmp/myfile.png"
# >> Filename.new(Filename.new(path)).to_s
# => path
#
# doctest: Filename can create a filepath from segments
# >> Filename.new("/tmp", "inner", "other.txt").to_s
# => "/tmp/inner/other.txt"
#
@filepath = File.join(*(segments.map{|s| s.to_s }))
end
@filepath
end
File.send(method, *([@filepath] + args), &proc)
end
end
3 Responses for "Working With File Names"
I think what you want is Pathname:
–> Pathname.new(’/foo/bar/baaz’).dirname
==> #
smart-quotes removed and pastied to gist - http://gist.github.com/2354 (ppl can fork + extend this very cool library)
@code_monkey_steve: Ah-hah! Thanks.
@Dr Nic: Thanks for posting. I hadn’t heard of gist. Is there a way to search and/or tag?
Leave a reply