在 ruby 中递归添加目录到 $LOAD_PATH 的最快方法是什么?

问题描述 投票:0回答:2

我想将vendor/gems/gems/**/lib 中的所有内容都放到加载路径上。我有办法做到这一点,但感觉很笨拙。 现在,我正在通过以下方式进行:

base = File.expand_path(File.join(File.dirname(__FILE__), "..", "vendor", "gems", "gems"))
libs = File.join(base, "**", "lib")
Dir.glob(libs) { |lib| $LOAD_PATH.unshift lib}

我确信有更好的方法来做到这一点。

ruby
2个回答
4
投票

我认为通过

File
设置基本路径就可以了。但您无需遍历目录列表即可将它们放入
$LOAD_PATH
中。您可以使用
unshift
并展开数组。

libs = File.expand_path("../../vendor/gems/**/lib", __FILE__)
$LOAD_PATH.unshift *Dir.glob(libs)

0
投票

我的解决办法是:

$LOAD_PATH.unshift *Dir.glob(File.expand_path("*/lib",__dir__))

例如

>> $LOAD_PATH.unshift *Dir.glob(File.expand_path("*/lib",__dir__))
=> 
["/Users/dorianmariefr/src/rails/actioncable/lib",
 "/Users/dorianmariefr/src/rails/actionmailbox/lib",
 "/Users/dorianmariefr/src/rails/actionmailer/lib",
 "/Users/dorianmariefr/src/rails/actionpack/lib",
 "/Users/dorianmariefr/src/rails/actiontext/lib",
 "/Users/dorianmariefr/src/rails/actionview/lib",
 "/Users/dorianmariefr/src/rails/activejob/lib",
 "/Users/dorianmariefr/src/rails/activemodel/lib",
 "/Users/dorianmariefr/src/rails/activerecord/lib",
 "/Users/dorianmariefr/src/rails/activestorage/lib",
 "/Users/dorianmariefr/src/rails/activesupport/lib",
 "/Users/dorianmariefr/src/rails/railties/lib",
 "/Users/dorianmariefr/src/rails",
 "/Users/dorianmariefr/.asdf/plugins/ruby/rubygems-plugin",
 "/Users/dorianmariefr/.asdf/installs/ruby/3.3.0/lib/ruby/gems/3.3.0/gems/rake-13.1.0/lib",
 "/Users/dorianmariefr/.asdf/installs/ruby/3.3.0/lib/ruby/gems/3.3.0/gems/reline-0.4.2/lib",
 "/Users/dorianmariefr/.asdf/installs/ruby/3.3.0/lib/ruby/gems/3.3.0/gems/irb-1.11.1/lib",
 "/Users/dorianmariefr/.asdf/installs/ruby/3.3.0/lib/ruby/site_ruby/3.3.0",
 "/Users/dorianmariefr/.asdf/installs/ruby/3.3.0/lib/ruby/site_ruby/3.3.0/arm64-darwin23",
 "/Users/dorianmariefr/.asdf/installs/ruby/3.3.0/lib/ruby/site_ruby",
 "/Users/dorianmariefr/.asdf/installs/ruby/3.3.0/lib/ruby/vendor_ruby/3.3.0",
 "/Users/dorianmariefr/.asdf/installs/ruby/3.3.0/lib/ruby/vendor_ruby/3.3.0/arm64-darwin23",
 "/Users/dorianmariefr/.asdf/installs/ruby/3.3.0/lib/ruby/vendor_ruby",
 "/Users/dorianmariefr/.asdf/installs/ruby/3.3.0/lib/ruby/3.3.0",
 "/Users/dorianmariefr/.asdf/installs/ruby/3.3.0/lib/ruby/3.3.0/arm64-darwin23"]
© www.soinside.com 2019 - 2024. All rights reserved.