如果无法访问源,则忽略 Gemfile `source`

Ignore Gemfile `source` if source not accessible

我们有一个内部 gem 服务器来存储一些特定于组织的 gem。我们通过 Gemfile:

中的源选项使用它
source 'https://local-gems.example.com' do
  gem 'local-gem'
end

内部gem服务器只能在内部网络上使用。

如果我断网了我可以 运行 bundle 如果:

  1. 我注释掉 source 声明(和关联的 end
  2. 源组中定义的 gem 已安装在系统上。

这意味着如果我在家工作,我需要记得注释掉 source 声明,然后记得在提交任何更改之前再次取消注释。

有没有办法修改Gemfile使其检测到源不可用并忽略它?也就是说,我是否可以配置 Gemfile,这样我每次离开本地网络工作时都不必注释掉这些行?

您可以向您的 Gemfile 添加任意 Ruby,这样您就可以执行以下操作:

if (some check if hostname resolves)
  source 'https://local-gems.example.com' do
    gem 'local-gem'
  end
end

例如,您可以这样使用 curl

local_source = if system('curl -s https://local-gems.example.com > /dev/null') != false
  # `curl` not available (`nil` returned) 
  #  or local gem server accessible (`true` returned) 
  #  try accessing:
  'https://local-gems.example.com'
else
  # Fall back on default behaviour
  'https://rubygems.org'
end

source local_source do
  gem 'local-gem'
end