What's the correct way to add a GitHub-hosted gem as a dependency in another gem?

Hey everyone! I’m working on a Ruby gem project and I’m stuck. I’ve got this base gem on GitHub that I want to use in another gem I’m developing. The base gem has a simple class in lib/screen/base.rb. I tried adding it to my Gemfile like this:

gem "my_base_gem", "~> 1.0.0", git: "[email protected]:myusername/my_base_gem.git"

Then in my new gem’s main file, I’m trying to require it:

require "my_base_gem"

But when I run it, I get this error:

LoadError: cannot load such file -- my_base_gem

It’s weird because if I add it to a Rails app’s Gemfile, it works fine. Any ideas on what I’m doing wrong or how to fix this? I feel like I’m missing something obvious here. Thanks in advance for any help!

yo, i think i know whats up. make sure ur gem’s lib folder has a file named after ur gem. like if ur gem is called ‘cool_gem’, u need ‘lib/cool_gem.rb’. inside that file, require the other files u need.

also, check if u’ve run ‘bundle install’ after adding the github gem. sometimes that fixes things.

hey there! i’ve run into this before. sounds like u might need to update ur gemspec file. try adding the github dependency there instead of the Gemfile. something like:

spec.add_dependency ‘my_base_gem’, ‘~> 1.0.0’, git: ‘[email protected]:myusername/my_base_gem.git’

hope that helps!

I’ve encountered similar issues when working with GitHub-hosted gems. One approach that’s worked well for me is to use the :github option in your gemspec instead of the git URL. Try modifying your gemspec file like this:

spec.add_dependency ‘my_base_gem’, ‘~> 1.0.0’, github: ‘myusername/my_base_gem’

This syntax is often more reliable for gem dependencies. Also, make sure you’re requiring the correct file path within your gem. Sometimes the file structure can be tricky. You might need to do:

require ‘screen/base’

instead of just requiring ‘my_base_gem’. This ensures you’re loading the specific file you need. Let me know if that helps or if you need more troubleshooting!

I’ve dealt with this issue before. The problem likely stems from how Ruby loads gems in development. When you’re working on a gem, the runtime doesn’t automatically load dependencies from the Gemfile.

Try adding this to your gem’s main file:

require 'bundler/setup'
Bundler.require(:default)

This initializes Bundler and requires all the gems specified in your Gemfile’s default group.

Also, ensure your gem’s lib directory is in the load path. You might need to add:

$LOAD_PATH.unshift File.expand_path('../lib', __FILE__)

at the top of your main file. This should resolve the loading issues you’re experiencing.