Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Implementation of 'which' in pure Ruby

Written by someone called 'erikh' on #rubyonrails on irc.freenode.net.

   1  module Which
   2   
   3    #
   4    # Searches the path, or a provided path with given separators
   5    # (path_sep, commonly ":") and a separator for directories (dir_sep,
   6    # commonly "/" or "\\" on windows), will return all of the places
   7    # that filename occurs. `filename' is included as a part of the
   8    # output.
   9    #
  10    # Those familiar with the which(1) utility from UNIX will notice the
  11    # similarities.
  12    #
  13   
  14    def which(filename, path=ENV["PATH"], path_sep=File::PATH_SEPARATOR, dir_sep=File::SEPARATOR)
  15      dirs = path.split(/#{path_sep}/)
  16   
  17      locations = []
  18   
  19      dirs.each do |dir|
  20        newfile = "#{dir}#{dir_sep}#{filename}"
  21        # strip any extra dir separators
  22        newfile.gsub!(/#{dir_sep}{2,}/, "#{dir_sep}")
  23        p = Pathname.new(newfile)
  24        if p.exist? and p.executable?
  25          locations.push(newfile)
  26        end
  27      end
  28   
  29      return locations
  30    end
  31   
  32    module_function :which
  33  end
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS