How do I temporarily change the require path in Ruby ($:)?
- by John Feminella
I'm doing some trickery with a bunch of Rake tasks for a complex project, gradually refactoring away some of the complexity in chunks at a time. This has exposed the bizarre web of dependencies left behind by the previous project maintainer.
What I'd like to be able to do is to add a specific path in the project to require's list of paths to be searched, aka $:. However, I only want that path to be searched in the context of one particular method. Right now I'm doing something like this:
def foo()
# Look up old paths, add new special path.
paths = $:
$: << special_path
# Do work ...
bar()
baz()
quux()
# Reset.
$:.clear
$: << paths
end
def bar()
require '...' # If called from within foo(), will also search special_path.
...
end
This is clearly a monstrous hack. Is there a better way?