๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

Ruby Gem Packaging

A gemspec describes a gem in plain Ruby code. This lesson builds a spec in code and compares versions with Gem::Version.

Build a spec in code

Gem::Specification.new runs the block with the new spec. Each line in the block fills one field, and the fields print afterwards.

spec = Gem::Specification.new do |s|
  s.name = "tiny-tools"
  s.version = "1.0.0"
  s.files = ["lib/tiny_tools.rb"]
  s.summary = "Small tools"
end
puts spec.name
puts spec.version
p spec.files

Compare versions by parts

Gem::Version reads each part as a number. The second part decides here, because 10 beats 9 even though the strings sort the other way.

old = Gem::Version.new "1.9.0"
newer = Gem::Version.new "1.10.0"
puts newer > old
puts newer == old
p newer.segments

A two-file gem lists both files

The files field holds every file the gem ships. Sorting the list gives a steady order for printing.

spec = Gem::Specification.new do |s|
  s.name = "tiny-tools"
  s.version = "0.2.0"
  s.files = ["lib/tiny_tools/cli.rb", "lib/tiny_tools.rb"]
  s.summary = "Small tools"
end
p spec.files.sort
puts spec.files.length

Example

spec = Gem::Specification.new do |s|
  s.name = "notebox"
  s.version = "2.1.0"
  s.files = ["lib/notebox/store.rb", "lib/notebox.rb"]
  s.summary = "Tiny notes"
end
current = spec.version
floor = Gem::Version.new "2.0.0"
puts spec.name
puts current > floor
p current.segments
p spec.files.sort

Key points

  • Gem::Specification.new builds a spec, and the block fills its fields.
  • The name and version fields answer as plain values.
  • The files field lists the files the gem ships.
  • Gem::Version compares versions one numeric part at a time.
  • segments answers the parts of a version as an array of numbers.

In this example, the block builds a complete spec for a two-file gem. The version stored in the spec compares greater than the floor version. The last lines list its parts and its sorted files.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why does Gem::Version read 1.10.0 as greater than 1.9.0?