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'
26
Dec 2011
CATEGORY

Tech

COMMENTS No Comments

Online Identities

A very prominent Rubyist has disappeared off the face of the internet, which has started me thinking about how we reconcile our online and offline identities.

I tend to leave everything in a giant jumble and try not to expose anything inappropriate. It’s not too hard, as I don’t really do anything that would get me in trouble. There are, however, many people on both sides and everywhere in between.  Read more →

24
Aug 2009
CATEGORY

Opinion

COMMENTS 1 Comment
TAGS

, , ,