4

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?

Jeffrey Aylesworth
  • 8,242
  • 9
  • 40
  • 57

3 Answers3

4

does File.expand_path help?

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

AShelly
  • 34,686
  • 15
  • 91
  • 152
3

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.

alloy
  • 20,908
  • 2
  • 30
  • 40
1

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!)

ennuikiller
  • 46,381
  • 14
  • 112
  • 137
  • how do you even get a 'symlink' on windows? – AShelly Dec 23 '09 at 19:11
  • You can't, but I need the script to work properly on Windows and *nix. (Windows does have a proprietary file format that acts like a symlink on Windows though, they're the .lnk files) – Jeffrey Aylesworth Dec 23 '09 at 20:39
  • A .lnk is just a file, not a filesystem feature, and its purpose is somewhat different. You can get Symbolic Links and Hard Links in Windows. I use them sometimes when I move a folder around and an old application requires the old path. You can find more information here: http://www.howtogeek.com/howto/windows-vista/using-symlinks-in-windows-vista/ – Anthony Michael Cook Jan 14 '13 at 07:27