0

I'm trying to avoid ever adding a redundant path to ruby's LOAD_PATH. It's not a remarkably complicated task, I'm just wondering if there is a cleaner method then what I've come up with.

This is my current solution as it stands now:

def add_loadpath(new_path)
  included = $LOAD_PATH.inject(false) do |acc,path|
    acc || new_path == File.expand_path(path)
  end
  $LOAD_PATH.unshift new_path unless included
end

Then instead of doing the usual $LOAD_PATH.unshift SOME_PATH you'd call
add_loadpath SOME_PATH

This is to avoid problems when the load path includes two paths that point to the same folder but are not the same string. For example foo/../bar and bar

Nathan Lilienthal
  • 864
  • 1
  • 10
  • 16

1 Answers1

0

I believe all paths in $LOAD_PATH are already expanded, so File.expand_path(path) is pointless. Your code can be refactored to this:

def add_loadpath(new_path)
  File.expand_path(new_path)
  .tap{|new_path| $LOAD_PATH.unshift(new_path) unless $LOAD_PATH.include?(new_path)}
end

or

def add_loadpath(new_path)
  $LOAD_PATH.unshift(File.expand_path(new_path)).uniq!
end
sawa
  • 165,429
  • 45
  • 277
  • 381
  • you're right that most of the time the `$LOAD_PATH` isn't tainted with relative paths, but there is nothing stopping someone from typing something like this, `LOAD_PATH.unshift '../../bin'` and breaking that convention. I'm trying to eliminate that possibility and also handle the possibility of a relative path. – Nathan Lilienthal Feb 10 '13 at 07:09