Monthly Archives: April 2008

Ever get frustrated dealing with files or directories in ruby? Maybe it’s just me, but using File, Dir, FileUtils, Pathname, etc makes me queasy. So I wrote POW! to make life easier.

Git it here http://github.com/probablycorey/pow

or sudo gem install pow

Since path manipulation is kind of boring, I’ll just give a few examples of how it’s helped me. Consider this directory structure…

/tmp
  /sub_dir
    /deeper_dir
  /extra_dir
  file.txt
  program
  README

To open a directory


path = Pow("tmp")

Open a file


Pow(:tmp, :sub_dir, :file.txt) do |file|
  # All the stuff you usually do with an open file!
  file.read
end


Check out what’s inside a directory


path = Pow("tmp")
path.each {|child| puts "#{child} - #{child.class.name}!" }

# Output!
# -------
/tmp/README - Pow::File
/tmp/subdir - Pow::Directory
/tmp/sub_dir/deeper_dir - Pow::Directory
/tmp/sub_dir/file.txt - Pow::File
/tmp/sub_dir/program - Pow::File
/tmp/extra_dir - Pow::Directory

Access a file in that directory


# The / operator accepcts symbols, strings or other Pow objects
file = path / :subdir / "file.txt"

# You can also use brackets to access paths
file = path[:subdir, "file.txt"]

Create nested directories


# Great for code generation

Pow("MOAR").create do
Pow("sub_dir").create do
Pow("info.txt").create do |file|
  file.puts "Here is the info you desired!"
end

Pow("README").create_file do |file|
  file.puts "I'm so glad you read this."
end

# Creates directory structure
/MOAR
  /sub_dir
    info.txt
  README

Sort a bunch of files by the modified date


Pow("images").files.sort_by {|file| file.modified_at}