Skip to content

Instantly share code, notes, and snippets.

@drnic
Created July 25, 2008 01:27
Show Gist options
  • Save drnic/2354 to your computer and use it in GitHub Desktop.
Save drnic/2354 to your computer and use it in GitHub Desktop.
Filename class for Ruby

Filename class

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.

Readme taken from original blog post

##
# 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"
#
# Authors: Duane Johnson
# Originally posted: http://blog.inquirylabs.com/2008/07/24/working-with-file-names/
class Filename
def initialize(*segments)
@filepath = File.join(*(segments.map{ |s| s.to_s }))
end
def to_s
@filepath
end
def method_missing(method, *args, &proc)
File.send(method, *([@filepath] + args), &proc)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment