Skip to content

Instantly share code, notes, and snippets.

@petekinnecom
Last active August 5, 2022 23:29
Show Gist options
  • Select an option

  • Save petekinnecom/075ac65607607776635fd118d701e0fd to your computer and use it in GitHub Desktop.

Select an option

Save petekinnecom/075ac65607607776635fd118d701e0fd to your computer and use it in GitHub Desktop.
# A small utility for requiring a gem that is not in your app's Gemfile.lock.
# It usually works. :)
#
# Example usage:
#
# Without BundlerBreakout:
#
# require 'mygem'
# LoadError: cannot load such file -- mygem
#
# With BundlerBreakout
# BundlerBreakout.require('mygem')
# defined?(Mygem)
# :constant
# 🎉
class BundlerBreakout
def self.require(*)
new(libname).load
end
def initialize(libname)
@libname = libname
end
def load
require @libname
rescue LoadError
$LOAD_PATH.unshift(*libs)
require @libname
end
private
def libs
# Rather than fuss around with private API for Bundler/Gem, we can
# shell out and see the effects on the $LOAD_PATH for requiring our
# gem. Is it ugly? Yes. Does it work? Yeah...mostly :)
clean_env do
out = <<~`SH`
ruby <<RUBY
pre = \\$LOAD_PATH.dup
require '#{@libname}'
puts \\$LOAD_PATH - pre
RUBY
SH
out.split("\n")
end
end
def clean_env(&block)
if defined?(Bundler)
Bundler.with_clean_env(&block)
else
block.call
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment