Rubygems: specify dependency on the latest version

2019-09-02 10:04发布

问题:

I'm developing a gem A that depends on another gem B. I need the user of my gem to have the latest version of B whatever it is. So I would like to say in my gemspec something like

spec.add_dependency "B", :latest

The reason for this is that B contains a database driver that needs to be in its latest version otherwise the database rejects the connection.

So in other words I need to force gem update before my gem is used. Is there a way how to do this in gemspec?

I know I can specify the version to be greater or smaller then some fixed version, but that's not what I want.

Also I can take the gem code from git - but taking it from master branch usually isn't the same as taking the latest "stable" version pushed to rubygems.

回答1:

How about something like this:

require 'json'
require 'uri'
require 'open-uri'

nokogiri_uri = URI('https://rubygems.org/api/v1/gems/nokogiri.json')

version = nil

open(nokogiri_uri) do |f|
  json_str = f.read
  puts json_str

  hash = JSON.parse json_str
  version = hash['version']
  puts version
end

if version
  spec.add_dependency "nokogiri", version
else
  puts "My gem won't work because its dependencies are buggered."

--output:--
{"name":"nokogiri","downloads":33177312,"version":"1.6.6.2", ... }
1.6.6.2

I used open-uri instead of the net/http library because of the article How to Cure Net::HTTP’s Risky Default HTTPS Behavior. I don't know if that concern has been addressed in the latest versions of ruby.