If I have a local gem (gemfile.gem) how can I get the name and version information from code or the command line without installing the gem.
Reason: I'm installing a user gem to validate it and want to uninstall it to clean up. User gem is not something I control so I can't depend on naming conventions.
CLI Solution:
gem spec gemfile.gem name
gem spec gemfile.gem version
Ruby Solution:
name = Psych.safe_load(`gem spec gemfile.gem name`).to_s
version = Psych.safe_load(`gem spec gemfile.gem version`, permitted_classes: [Gem::Version]).to_s
# Now you can uninstall the gem with
Gem::Uninstaller.new(name, {:version => version, :force => true}).uninstall
CodePudding user response:
You can see locked version in Gemfile.lock
cat Gemfile.lock | grep gem-name
Other option, but need bundle install
first
bundle exec gem dependency | grep gem-name
Update:
If you need to check local gem version, for example some-gem.gem
, you can use such command to parse all information from binary
gem specification some-gem.gem
or just
gem spec some-gem.gem
You can also look it with Ruby format
gem spec some-gem.gem --ruby
Of course you can use grep
to filter lines with version
word
But it's better to pass it as argument like this
gem spec some-gem.gem version
CodePudding user response:
Your question is ambiguous. If you mean "How can I read in the gem name and version from the gemspec?" then you can use the output of Gem::Specification#load. For example, assuming you have a gem with a standard layout and foo_bar.gemspec
in the root of your gem's project directory, you can use Git to find the top-level of your project and read in the gemspec:
$ cd "$(git rev-parse --show-toplevel)
$ ruby -e 'puts Gem::Specification.load "#{File.basename Dir.pwd}.gemspec"'
#<Gem::Specification name=foo_bar version=0.1.0>
You can then parse the output with sed, awk, or cut.
CodePudding user response:
A Gemfile
does not (necessarily) specify an exact version of a dependency. It might specify nothing (i.e. "any version is fine"), or ~> 1.0
(i.e. >= 1.0
and < 2.0
), or whatever. Also, dependency constraints might further restrict the valid range of versions.
I'm assuming that this isn't what you meant by your question. Instead, you'd like to know what exact versions of dependencies will be installed by running bundle install
, given a Gemfile.lock
.
One way to achieve this reliably (i.e. rather than using grep
and eyeballing which line(s) are most relevant) is by parsing the Gemfile.lock
:
require 'bundler'
lockfile = Bundler::LockfileParser.new(Bundler.read_file('Gemfile.lock'))
puts lockfile.specs.find { |spec| spec.name == 'the-gem-you-want-to-check' }.version