Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a local gem from a ruby script?

Tags:

ruby

bundler

gem

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?

like image 971
tohokami Avatar asked Nov 25 '12 09:11

tohokami


People also ask

How do I install a specific version of a gem?

Use `gem install -v` You may already be familiar with gem install , but if you add the -v flag, you can specify the version of the gem to install. Using -v you can specify an exact version or use version comparators.

Where is the gem file located?

The Gemfile is wherever you want it to be - usually in the main directory of your project and the name of the file is Gemfile . It's convenient to have one because it allows you to use Bundler to manage which gems and which versions of each your project needs to run.

Where are gems stored Ruby?

The main place where libraries are hosted is RubyGems.org, a public repository of gems that can be searched and installed onto your machine. You may browse and search for gems using the RubyGems website, or use the gem command. Using gem search -r , you can search RubyGems' repository.


1 Answers

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
like image 76
user1790619 Avatar answered Oct 17 '22 16:10

user1790619