How do I temporarily change the require path in Ruby ($:)?

Posted by John Feminella on Stack Overflow See other posts from Stack Overflow or by John Feminella
Published on 2010-04-24T19:14:00Z Indexed on 2010/04/24 19:23 UTC
Read the original article Hit count: 244

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about rake

Related posts about require