Peter Marklund

Peter Marklund's Home

Mon June 16, 2008
Programming

Ruby Gotcha: Symlinked Scripts and File.dirname(__FILE__)

If you have a Ruby script say in ~/src/ruby/my_script that you are symlinking to from ~/bin/my_script, then invoking File.dirname(__FILE__) in that script will yield the directory of the symlink not the directory of the script file. If you want the directory of the script file you can do this instead:

THIS_FILE = File.symlink?(__FILE__) ? File.readlink(__FILE__) : __FILE__

THIS_FILE will contain the path to the script file instead of the path to the symlink. This is valuable if say you want to require some Ruby library from your script and you are using a relative path.

Comments

Duane Johnson said about 1 month ago:

Thanks! That was just what I was looking for.

--------------------------------------------------------------------------------

Leave a Comment


(leave url/email »)


Use plain text for your comments. HTML will be quoted. URLs will be turned into hyperlinks. Linebreaks will be preserved.