Skip to content

Instantly share code, notes, and snippets.

@khiav223577
Created January 21, 2019 17:31
Show Gist options
  • Save khiav223577/01b410a1a8238f746dd3ec1830dbeb51 to your computer and use it in GitHub Desktop.
Save khiav223577/01b410a1a8238f746dd3ec1830dbeb51 to your computer and use it in GitHub Desktop.
module Kernel
def require_outer_gem(path)
gem_path = "#{Gem.path.first}/gems"
extract_gem_name = ->(gems_paths){ gems_paths.map{|s| s[/gems\/([^\/]+)\/lib$/, 1] }.compact }
outer_gems = extract_gem_name[Dir["#{gem_path}/*/lib"]] - extract_gem_name[$LOAD_PATH]
outer_gems = outer_gems.lazy
.map{|s| s.rpartition('-') }
.map{|gem_name, _, version| [gem_name, version] }
.sort_by{|_, v| Gem::Version.new(v) } # 多版本的話選最新版號
.reverse
.to_h
.to_a
.map{|s| s.join('-') }
origin_load_paths = $LOAD_PATH.clone
begin
$LOAD_PATH.concat(outer_gems.map{|s| "#{gem_path}/#{s}/lib" })
require(path)
ensure
$LOAD_PATH.clear
$LOAD_PATH.concat(origin_load_paths) # 還原原本的 $LOAD_PATH
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment