How can I install a gem (via bundler using gemspec) before parsing the gemspec?

我的梦境 提交于 2019-12-11 16:17:55

问题


I have a gem that exists for the purpose of helping with versioning. It's useful to have this gem available when defining the version in the gemspec file.

The problem, however, is that running bundle install first causes the gemspec to be parsed, which results in an error because the required gem isn't installed yet.

I can get around it by running gem install <other_gem> before bundle install, but I'd much prefer bundler manage it, especially when taking into account that I'm using a custom gem server.

I've tried adding the gem to the Gemfile directly before the gemspec line, but no luck.

Gemfile:

source 'https://my.gemserver.com/gems'

gemspec

mygem.gemspec:

require 'external/dependency'

Gem::Specification.new do |spec|
  spec.name = 'mygem'
  spec.version = External::Dependency.version_helper
  ....
  spec.add_development_dependency 'external-dependency'
end

EDIT: Another workaround is to rescue the LoadError and specify a default version if the dependency isn't loaded. Also, not ideal

begin
  require 'external/dependency'
rescue LoadError; end

Gem::Specification.new do |spec|
  spec.name = 'mygem'
  spec.version = defined?(External::Dependency) ? External::Dependency.version_helper : ''
  ....
  spec.add_development_dependency 'external-dependency'
end

回答1:


I think you're stuck with gem install. But I would solve this by adding that step to the Dockerfile I use for the project.

Maybe it's possible to do something like this using rbenv or rvm? Haven't used either of those since migrating to Docker, but rvm gemset is kind of a bootstrap...




回答2:


I got around it by making the gemspec install the gem during a bundle update or install.

EXTERNAL_DEPENDENCY = Gem::Dependency.new('external-dependency', '~> 0.1')
if File.basename($0) == 'bundle' && ARGV.include?('update') || ARGV.include?('install')
  require 'rubygems/dependency_installer'
  Gem::DependencyInstaller.new.install(EXTERNAL_DEPENDENCY)
end

and then...

spec.add_development_dependency EXTERNAL_DEPENDENCY.name, EXTERNAL_DEPENDENCY.requirements_list


来源:https://stackoverflow.com/questions/51564195/how-can-i-install-a-gem-via-bundler-using-gemspec-before-parsing-the-gemspec

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!