Gem Writing: Private Gem Dependencies

rubies

When you are working in a Ruby shop that doesn’t completely subscribe to the Majestic Monolith™ mindset, you’ll probably end up with some domain logic that needs to be shared across your apps/services. In Ruby Land, that means encapsulating that logic into a gem, so all of your applications can have consistent logic.

2001-monolith-monkeys

When doing this in a work context, the gems in question are probably private, and hosted somewhere other than RubyGems. Normally this is fine, there are plenty of hosting solutions for private gems. The problems start when you need a private gem as a dependency of another private gem.

In a Gemfile, you have the ability to define whatever alternate sources you want for a gem with:

gem 'my-gem', source: "https://token@gem.fury.io/ramico/"

But if you try this when you declare a dependency in a gem, you’re gonna have a bad time. In a gemspec, add_runtime_dependency will only accept the name of a gem and a version, no source allowed.

this-is-the-worst

After a couple of days of digging, I finally discovered a thread to solve the dilemma. So to include a private gem “dependent-gem” as a dependency for a gem “my-main-gem”, add the source to my-main-gem’s Gemfile:

source "https://token@gem.fury.io/ramico/" do
  gem 'dependent-gem'
end

Then in my-main-gem’s gemspec:

Gem::Specification.new do |spec|
  spec.add_runtime_dependency "dependent-gem", "~> 1.0"
end

Now when you include “my-main-gem” in your app, it will ALSO properly load gem “dependent-gem” from your private gem repo!

more-you-know

%d bloggers like this: