2

I have a gem that I created in Ruby on my local machine and I need to require this gem in a plain Ruby script that starts a service.

I have to require like this:

require_relative '../../../my-gem/lib/my/gem'

Is it possible to do this require without putting in the relative path?

Andrew Myers
  • 2,754
  • 5
  • 32
  • 40
edymerchk
  • 1,203
  • 13
  • 19
  • Is it in your gem path folder? Did you install it somehow or it just sits in a random folder? – Agis Mar 11 '14 at 17:38
  • I installed the gem with rake install, I just checked and my gem appears in /home/user/.rbenv/versions/2.1.1/lib/ruby/gems/2.1.0/gems – edymerchk Mar 11 '14 at 18:36
  • And doesn't a simple `require 'yourgem'` works? – Agis Mar 11 '14 at 19:02
  • Possible duplicate of [How to reference a local gem from a ruby script?](https://stackoverflow.com/questions/13549963/how-to-reference-a-local-gem-from-a-ruby-script) – Brian Kung Jun 22 '19 at 20:14

2 Answers2

2

require checks for files in $LOAD_PATH. You can put your gem in one of those directories in order to require it directly. If you don't like your load path, you can add a new directory to it in your script, or set the RUBYLIB environment variable which is added to the load path.

Max
  • 21,123
  • 5
  • 49
  • 71
1

If you have a gem, you can install it and set the version you want (in my example 1.0.0.beta) with gem 'my-gem', '= 1.0.0.beta'.

But I think yu look for another solution:

You can extend the location where require looks:

$:.unshift('../../../my-gem/lib')
require('my/gem')

or

$LOAD_PATH.unshift('../../../my-gem/lib')
require('my/gem')

You could also use $: << '../../../my-gem/lib', but I prefer unshift. If your gem contains a file with similar names as in a gem (avoid it!), then unshift guarantees your script is loaded.

knut
  • 27,320
  • 6
  • 84
  • 112