views:

59

answers:

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?

+1  A: 

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
That wont work on Windows though.
Jeffrey Aylesworth
how do you even get a 'symlink' on windows?
AShelly
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
+2  A: 

does File.expand_path help?

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

AShelly
yes that resolves symlinks (at least on mac osx)
ennuikiller
Not working on mine, also OS X. Maybe there's an option that needs to be set for it to do that? I'm using `File.dirname(File.expand_path(__FILE__))`
Jeffrey Aylesworth
I'm just using File.expand_path(".") for a symlinked dir. I'm running ruby 1.9 on max osx 10.6
ennuikiller
I was using ruby 1.8, but installed 1.9 and still didn't work. I'll just write a function to test if it's a symlink, and follow if it is.
Jeffrey Aylesworth
@Jeffrey Aylesworth: try reversing those operations: `File.expand_path(File.dirname(__FILE__))`
James A. Rosen
A: 

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
A: 

Does Dir.pwd fall into the same issue?

Beanish
Yes, that gives me the current working directory, which isn't always what I want.
Jeffrey Aylesworth