How to get the directory of the current script?

Hi,

How do I get the directory path of the file that is currently
executing?

Also, if I have a module, within a function, how do I get the parent
directory (full path) of that module?

Thanks, - Dave

Hi,

File.dirname(FILE) will give you the current file’s path. For
your second question, there’s no way to do that, unless your code
follows strict code conventions (a-la Rails), or the module provides a
way to query that information.

Hope that helps !
François

2008/2/20, laredotornado [email protected]:

File.dirname(FILE) will give you the current file’s path.

The current file may be accessed with a relative path. If you need the
absolute path,
make sure you expand it: File.expand_path(File.dirname(FILE))

Also, if I have a module, within a function, how do I get the parent
directory (full path) of that module?

If FILE is used in that module, it will refer to the file containing
that module.
If the module is under your control, you can add a method that provides
this:

module MyModule
def this_file
FILE
end
end

Otherwise, as has been noted, since a module name does not have to have
any
relation to the filename it is in, there is no way (AFAIK) to find the
file containing a
particular module unless you open the current file and parse for any
require
or load calls (recursively using the current environment for searching
for files)
and look for the module declaration line. (Note that a file may have
been required
using a path, so you must parse the current script to find where files
have been
located.)

Of course, a module could have content added in multiple files…

On 02.01.2010 03:33, Kimball Johnson wrote:

As to getting the parent directory of a file, try this:

File.dirname(File.dirname(FILE))

or for the absoluter path:

File.expand_path(File.dirname(File.dirname(FILE)))

dumb but smart?

require “futils”
puts Dir.pwd

laredotornado wrote:

Hi,

How do I get the directory path of the file that is currently
executing?

Also, if I have a module, within a function, how do I get the parent
directory (full path) of that module?

Thanks, - Dave

As to getting the parent directory of a file, try this:

File.dirname(File.dirname(FILE))

or for the absoluter path:

File.expand_path(File.dirname(File.dirname(FILE)))

dumb but smart?

Phillip G. wrote:

On 02.01.2010 03:33, Kimball Johnson wrote:

As to getting the parent directory of a file, try this:

File.dirname(File.dirname(FILE))

or for the absoluter path:

File.expand_path(File.dirname(File.dirname(FILE)))

dumb but smart?

require “futils”
puts Dir.pwd

Note 1: the process’s current working directory is in general unrelated
to the directory where the script itself is located.

Note 2: you don’t need to load any library to get access to Dir.pwd