File path operations?

K

Kenneth McDonald

Ruby has an abstract File/path type which is nice (I'm mainly a Python
user and it doesn't), but it doesn't seem to provide object-oriented
methods to combine file paths, i.e. I can't go path3 = path1/path2 or
something similar. Instead, I have to use the join function, which is
much less elegant, IMHO. Am I missing something. Has someone written
an extension to File that adds such path operations?

Thanks,
Ken
 
R

Robert Klemme

2008/9/22 Kenneth McDonald said:
Ruby has an abstract File/path type which is nice (I'm mainly a Python user
and it doesn't), but it doesn't seem to provide object-oriented methods to
combine file paths, i.e. I can't go path3 = path1/path2 or something
similar. Instead, I have to use the join function, which is much less
elegant, IMHO. Am I missing something. Has someone written an extension to
File that adds such path operations?

irb(main):001:0> require 'pathname'
=> true
irb(main):002:0> pn = Pathname.new '.'
=> #<Pathname:.>
irb(main):003:0> pn.absolute?
=> false
irb(main):004:0> pn + "foo" + "bar"
=> #<Pathname:foo/bar>

Cheers

robert
 
K

Kenneth McDonald

Thanks!
irb(main):001:0> require 'pathname'
=> true
irb(main):002:0> pn = Pathname.new '.'
=> #<Pathname:.>
irb(main):003:0> pn.absolute?
=> false
irb(main):004:0> pn + "foo" + "bar"
=> #<Pathname:foo/bar>

Cheers

robert
 
M

Mike Gold

I went for years without knowing about Pathname. It seems rather
underused.

The singleton methods File.basename, File.exist?, etc. are awkward
because the proper abstraction is a path, not an arbitrary string.
Moreover, these methods cut against the natural flow of ruby code.
Compare

File.join File.dirname(foo), "intermediate", File.basename(foo)

with

foo.dirname.join "intermediate", foo.basename

I would like to see more ruby packages use Pathname. If your method
takes a string argument, then use it as a string. However if your
method takes a path name disguised as a string, consider taking a
Pathname. (In practice I expect you'd convert any non-Pathnames to
Pathnames.)

Now that Pathname has been in the standard library since 1.8.0, perhaps
it is time for the whole standard library to use it? It certainly makes
code cleaner and clearer.

It also discourages the use of problematic "#{x}/#{y}" constructs. If x
is nil, you are now pointing at the root directory, with not a peep of
warning from ruby.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,648
Latest member
NREEugene

Latest Threads

Top