我目前有一个安装程序可以安装一组 ruby 脚本(这是主程序的可选安装)。我写了一个脚本,在安装后,它会扫描包含的 ruby 文件中的所有 require 语句,然后提取所有“必需”文件。例如,它会寻找
require 'curb'
require 'rest-client'
# require etc...
在每个文件中,然后将它们包含在列表中(删除重复项)所以我有一个数组,如下所示:
"curb", "rest-client", etc...
对于大多数 gem 来说,它非常好,因为名称匹配,我只是做了一个
gem install GEMNAME
在名称不匹配的情况下,我试图通过查询 gem 服务器找出一种从 require 行中找出 gem 名称的方法。例如:
xml-simple 有一个 xmlsimple 的 require 语句,但是 gem 是 xml-simple。经过大量搜索,我能找到的唯一“解决方案”是安装每个 gem 并检查文件是否包含在
gem specification GEMNAME
这远非最佳,实际上是一个非常糟糕的主意,我想知道是否有一种方法可以查询 rubygems 以查看 gem 中包含哪些文件。
最佳答案
Rubygems 有一个 API使用搜索端点:
/api/v1/search.(json|xml|yaml)?query=[YOUR QUERY]
搜索端点列在 Gem Methods .我相信这个搜索可以用来做你想做的事,也许通过提供部分名称并使用正则表达式来过滤结束匹配。
编辑: 看看 Bundler 也可能有用gem 本身,因为如果我没记错的话,当你打错字时他们有时会推荐 gems。
更新:
我会遵循这样的工作流程:
尝试安装需要的 gem。
如果出现错误,请选择 gemname 的几段,比如 gem_name_str[0..5]
、gem_name_str[0..4]
和 gem_name_str[0..3]
.
使用这些字符串查询 API。
删除重复项
使用动态生成的正则表达式测试返回的值。像这样的东西:
#given @param name = string from 'require' statement
values_returned_from_api.each do |value|
split_name = name.split(//)
split_value = value.split(//)
high_mark = 0
#this will find the index of the last character which is the same in both strings
for (i in 0..split_name.length) do
if split_name[i] == split_value[i]
high_mark = i
else
break
end
end
#this regex will tell you if the names differ by only one character
#at the point where they stopped matching. In my experience, this has
#been the only way gem names differ from their require statement.
#such as 'active_record'/'activerecord', 'xml-simple'/'xmlsimple' etc...
#get the shorter name of the two
regex_str = split_name.length < split_value.length ? split_name : split_value
#get the longer name of the two
comparison_str = split_name.length < split_value.length ? value : name
#build the regex
regex_str.insert((high_mark + 1), '.') #insert a dot where the two strings differ
regex = /#{regex_str.join('')}/
return name if comparison_str =~ regex
end
注意:此代码未经测试。它只是为了说明这一点。它也可能被优化和压缩。
我假设 API 返回部分匹配项。我还没有实际尝试过。
关于ruby - 从代码中的 require 行中查找 gem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7532979/