Jeffrey Aylesworth
Jeffrey Aylesworth

Reputation: 8540

Accessing files in the same directory as script

I need to access files that are relative to the location of my Ruby script.

The only solution I've found is using File.dirname(__FILE__), however, if the script is run from a symlink, __FILE__ gives the location of the symlink.

I would prefer a solution that does not involve looking at __FILE__, checking if it's a link, if it is, finding out where it points to. But, if there is no other way, it would be nice to know if there is already a gem to do this?

Upvotes: 4

Views: 1971

Answers (3)

alloy
alloy

Reputation: 21048

I prefer the following variant: File.expand_path('../other_file_in_same_dir', __FILE__)

The second argument is the point from where the relative path will get expanded. This defaults to the current working directory.

Upvotes: 3

AShelly
AShelly

Reputation: 35600

does File.expand_path help?

(don't have a 'nix box to try it on)

Upvotes: 4

ennuikiller
ennuikiller

Reputation: 46985

You could always execute a shell command like ls -l $(pwd) with popen and parse it to follow the symlink. For windows you would simply execute the equivalent windows os command (which I'm assuming exists!)

Upvotes: 1

Related Questions