Introducing static_paths 0.1.0

Update: Documentation has now been posted on static-paths.rubyforge.org.

When writing a library which bundles static-content in a directory named data/ or static/, you usually need to find the directory using something like File.expand_path(File.join(File.dirname(__FILE__),'..','..','..','..','static)).

But then you want to allow plugins to extend the functionality of your library, and even add their own static-content. Now you have to manage more than one directory path.

Enter StaticPaths, a Ruby library for managing and searching through directories containing static-content. StaticPaths helps manage directories across multiple libraries in much the same way that RubyGems manages lib/ directories using $LOAD_PATH. Except that StaticPaths does not use global variables.

Example Usage

require 'static_paths'

module MyLibrary
  include StaticPaths

  # define the static dir(s)
  register_static_dir File.join(File.dirname(__FILE__),'..','..','static')
end

register_static_dir will expand the path, make sure the path points to a directory, then adds the path to StaticPaths.paths and the local MyLibrary.static_paths.

One can also unregister directories using unregister_static_dir!.

MyLibrary.unregister_static_dir! File.join(File.dirname(__FILE__),'..','..','static')

Or, one can use unregister_static_dirs! to unregister all directories registered within a module/class.

module MyLibrary
  def MyLibrary.cleanup!
    unregister_static_dirs!
  end
end

To search through and access the content within registered directories, simply use the methods within the StaticPaths::Finders module.

module MyLibrary
  class UsesContent

    include StaticPaths::Finders

    def index
      find_static_file('index.html')
    end

    def file_dirs
      all_static_dirs('extra')
    end

    def copy(src,dest)
      each_static_dir(src) do |dir|
        FileUtils.cp_r(dir,dest)
      end
    end

  end
end

Installation:

$ sudo gem install static_paths
About these ads

About this entry