Search code examples
rubygitrubygemsbundle

Unable to load gem installed from git source (LoadError: cannot load such file)


I have create a gem named registry_client in a monorepo structure. With the hope that I can use it internally in my frontend-app. However, I encountered this error when I try to run it with bundler bundle exec ruby app.rb:

LoadError: cannot load such file -- registry_client

The Gemfile in frontend-app:

source 'https://rubygems.org'

gem 'registry_client', git: 'https://github.com/.../some_repo.git', branch: 'master', glob: 'registry-client/*.gemspec'

I verified the gem is successfully installed after bundle install with bundle list:

Gems included by the bundle:
  ...
  * registry_client (0.1.1 f93f5bd)
  ...

This the repo structure:

├── frontend-app
│   ├── Gemfile
│   ├── Gemfile.lock
│   ├── Rakefile
│   ├── app.rb
│   ├── config
│   ├── config.ru
│   ├── test
│   └── views
└── registry-client
    ├── Gemfile
    ├── lib
    ├── registry_client.gemspec
    └── test

app.rb

require 'registry_client'

...

registry_client.gemspec

# frozen_string_literal: true

require_relative 'lib/version'

Gem::Specification.new do |spec|
  spec.name          = 'registry_client'
  spec.summary       = 'Registry client for using Redis as Service Registry.'
  spec.authors       = ['Author']
  spec.version       = RegistryClient::VERSION
  spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')

  # Specify which files should be added to the gem when it is released.
  # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
  spec.files = Dir.chdir(File.expand_path(__dir__)) do
    `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
  end
  spec.bindir        = 'exe'
  spec.executables   = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
  spec.require_paths = ['lib']
end

Edit: added gemspec file


Solution

  • The require method looks through the directories in the $LOAD_PATH and tries to find a file with the name that matches the argument registry_client. The spec.required_paths attribute in the gemspec specifies:

    Paths in the gem to add to $LOAD_PATH when this gem is activated. The default value is "lib"

    Therefore, your lib directory must have a file named registry_client (in your case, it will have .rb extension). More on this here: https://guides.rubygems.org/patterns/#loading-code