Last active
August 5, 2022 23:29
-
-
Save petekinnecom/075ac65607607776635fd118d701e0fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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