Skip to content

Instantly share code, notes, and snippets.

@jugyo
Created October 27, 2010 01:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jugyo/648232 to your computer and use it in GitHub Desktop.
Save jugyo/648232 to your computer and use it in GitHub Desktop.
force_require for bundler
# force_require.rb
#
# == Usage
#
# require 'bundler/setup'
# require './force_require'
#
# force_require 'g'
# g 'foo'
#
# require 'g' # => LoadError
#
module Kernel
def new_require(name)
begin
org_require name
rescue LoadError
if Thread.current[:force_require_mode]
force_require name
else
raise
end
end
end
alias_method :org_require, :require
alias_method :require, :new_require
def force_require(name)
Thread.current[:force_require_mode] = true
Gem.all_load_paths.each do |dir|
Dir[File.join(dir, "#{name}#{Gem.suffix_pattern}")].each do |file|
require file
return true
end
end
raise LoadError, "no such file to load -- #{name}"
ensure
Thread.current[:force_require_mode] = false
end
alias_method :require!, :force_require
end
@nahi
Copy link

nahi commented Oct 27, 2010

It'd be better of using TLS instead of global variable.

@jugyo
Copy link
Author

jugyo commented Oct 27, 2010

what is TLS?

@nagachika
Copy link

It seems that TLS = Thread Local Storage.

BTW, I wonder if recursive call should be considered too. doesn't it?

ex)

begin
  orig, Thread.current[:__force_require] = Thread.current[:__force_require], true
  ...
ensure
  Thread.current[:__force_require] = orig
end

@jugyo
Copy link
Author

jugyo commented Oct 27, 2010

I get it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment