hoodwink.d enhanced


How Powerful Pathname Is #

by daigo in bits

How powerful Pathname is! Unfortunately I did not know. Have you ever been annoyed which class to use, File, FileTest, Dir or Find? Use Pathname, instead. That’s all (on UNIX platforms). The Pathname class, included in the Ruby 1.8 standard libraries, represents paths of directories and files, and is a facade to File, FileTest, Dir and Find.

You can see some examples in the header lines of the source:

   require 'pathname'
   p = Pathname.new("/usr/bin/ruby")
   size = p.size              # 27662
   isdir = p.directory?       # false
   dir  = p.dirname           # Pathname:/usr/bin
   base = p.basename          # Pathname:ruby
   dir, base = p.split        # [Pathname:/usr/bin, Pathname:ruby]
   data = p.read
   p.open { |f| _ } 
   p.each_line { |line| _ }

That means

   p = "/usr/bin/ruby" 
   size = File.size(p)        # 27662
   isdir = File.directory?(p) # false
   dir  = File.dirname(p)     # "/usr/bin" 
   base = File.basename(p)    # "ruby" 
   dir, base = File.split(p)  # ["/usr/bin", "ruby"]
   data = File.read(p)
   File.open(p) { |f| _ } 
   File.foreach(p) { |line| _ }

Pathname has exist?, file?, mkdir, rmdir, rmtree, children, find and so on as well.

said on 08 Jun 2005 at 09:33

I really love Pathname. It makes working with files quite easy. It does have a few occasional oddities with Windows, but that’s understandable ;)

said on 08 Jun 2005 at 15:28

I believe my feelings on this subject are well known.

As for Windows, netghost, I have a package called win32-pathname checked into CVS at http://www.rubyforge.org/projects/win32utils.

said on 08 Jun 2005 at 17:33

Wow! Thanks for pointing out this gem for me. I’m definitely going to be requring ‘pathname’ in the future.

said on 09 Jun 2005 at 04:13

It’s really nice. The only things I come across with that it doesn’t do is copying files (understandable, you need 2 files) and recursively deleting a directory: for that FileUtils.rm_rf is still needed.

But indeed, definitely candidate for ‘most useful ruby lib’.

said on 11 Jun 2005 at 15:52

And so, pathname2 was unleashed upon the world…

Comments are closed for this entry.