Read more

How to get information about a gem (via CLI or at runtime from Ruby)

Arne Hartherz
March 14, 2022Software engineer at makandra GmbH

When you need information about a gem (like version(s) or install path(s)), you can use the gem binary from the command line, or the Gem API inside a ruby process at runtime.

gem binary (in a terminal)

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

You can get some information about a gem by running gem info <gem name> in your terminal.

Example:

$ gem info irb

*** LOCAL GEMS ***

irb (1.4.1, 1.3.5)
    Author: Keiju ISHITSUKA
    Homepage: https://github.com/ruby/irb
    Licenses: Ruby, BSD-2-Clause
    Installed at (1.4.1): /home/arne/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0
                 (1.3.5, default): /home/arne/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0

    Interactive Ruby command-line tool for REPL (Read Eval Print Loop).

Type gem help info to see a list of available switches.

Note that the Ruby API offers a bit more insight.

Gem Ruby API (at runtime)

First, get the Gem::Specification of the gem you are looking for.
That object holds all the information from the gem's gemspec file, and more (like paths).

Note that this reflects the gem version that is currently loaded.

>> Gem.loaded_specs['irb']
=> 
Gem::Specification.new do |s|
  s.name = "irb"
  s.version = Gem::Version.new("1.4.1")
  s.installed_by_version = Gem::Version.new("3.3.9")
  s.authors = ["Keiju ISHITSUKA"]
  s.bindir = "exe"
  s.date = Time.utc(2021, 12, 25)
  s.dependencies = [Gem::Dependency.new("reline", Gem::Requirement.new([">= 0.3.0"]), :runtime)]
  s.description = "Interactive Ruby command-line tool for REPL (Read Eval Print Loop)."
  s.email = ["keiju@ruby-lang.org"]
  s.executables = ["irb"]
  s.files = ["exe/irb"]
  s.homepage = "https://github.com/ruby/irb"
  s.licenses = ["Ruby", "BSD-2-Clause"]
  s.require_paths = ["lib"]
  s.required_ruby_version = Gem::Requirement.new([">= 2.5"])
  s.rubygems_version = "3.3.9"
  s.specification_version = 4
  s.summary = "Interactive Ruby command-line tool for REPL (Read Eval Print Loop)."
  end

All of those properties from the inspection above are available as methods. There are more methods from Gem::Specification Show archive.org snapshot and Gem::BasicSpecification Show archive.org snapshot available. Examples:

>> Gem.loaded_specs['irb'].full_name
=> "irb-1.4.1"
>> Gem.loaded_specs['irb'].gem_dir
=> "/home/arne/.rbenv/versions/3.0.3/lib/ruby/gems/3.0.0/gems/irb-1.4.1"
>> Gem.loaded_specs['irb'].activated?
=> true
Arne Hartherz
March 14, 2022Software engineer at makandra GmbH
Posted by Arne Hartherz to makandra dev (2022-03-14 10:02)