Search code examples
rubyrubygemsbundler

How to reference a local gem from a ruby script?


I need to reference a local gem from a plain ruby script, without installing the gem. On the trail of How to refer a local gem in ruby?, i tried creating a Gemfile with the following setup:

%w(
  custom_gem
  another_custom_gem
).each do |dependency|
  gem dependency, :path => File.expand_path("../../#{dependency}", __FILE__)
end

and the script looks like this:

require 'custom_gem'
CustomGem::Do.something

When I execute this with:

bundle exec ruby script.rb

I get:

script.rb:1:in `require': cannot load such file -- custom_gem (LoadError) from script.rb:1:in `<main>'

If I leave out the require 'custom_gem' , I get:

script.rb:3:in `<main>': uninitialized constant CustomGem (NameError)

I even tried without bundler, and just writing gem ... :path =>̣ ... in the script itself, but without results. Is there any other way of referencing custom gems from ruby scripts, without installing the gems locally?


Solution

  • Make sure that your gem name as same as in Gemfile (e.g. custom_gem)

    # Gemfile
    
    source "https://rubygems.org"
    
    gem "custom_gem", path: "/home/username/path/to/custom_gem"
    

    Don't forget to actually install this gem using bundler

    bundle install
    

    After that, the script should be ready to use by bundle exec ruby script.rb

    # script.rb
    
    require 'custom_gem'
    CustomGem::Do.something