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}

2 Comments

  1. As stolen from various of my projects. Feel free to hack some out of it, should simplify your argument structs.


    class File
    module Pathize
    def / other
    File.join(self.to_s, other.to_s)
    end
    end

    Extensions = %r=^(markdown|textile|haml|sass|css|html|xhtml|rb|txt|text|atom|rss|xml)$=i
    module Extension
    def method_missing(meth, *args)
    if Extensions =~ meth.to_s
    [self, '.', meth.to_s].join
    else
    super
    end
    end
    end
    end

    class String
    include File::Extension
    include File::Pathize
    end
    class Symbol
    include File::Extension
    include File::Pathize
    end

    Then you should be able to do…


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

  2. Ack, just noticed you already have something similar in place!

    Also, you might wanna let commenters use that sexy code-box you have set up. My comment looks fuuuugly on my end.

One Trackback/Pingback

  1. [...] POW! [...]

Post a Comment

*
*