Ruby 1.8, resolve symlink recursively.

Ruby 1.9 has added a bunch of niceties in the file class that allow you to find the absolute real path of a file (IE, no symlinks). Here’s a quick snippet that you can use in 1.8 to do the same thing. I’m specifically using this in a utility that will likely be symlimked into /sbin, but i’ve still got to load libraries and configs.

You can replace “$LOAD_PATH” with “$:”, but I find the long form more readable.

file_path = __FILE__
while File.symlink?(file_path) do
  file_path = File.dirname(file_path) +'/'+ File.readlink(file_path)
end
#this is your real path. For example only.
puts "resolved path: #{file_path}"

# add your lib directory to the load path.
# Two directories up, as i'm keeping my primary .rb file in project_dir/bin
# search our libraries first to give priority above system installed libs.
$LOAD_PATH.unshift File.expand_path("../../lib/",file_path)
# require something from your lib directory
require 'mylib/lib.rb'

Comments are closed.