Executable "require" can't find it's own library

1.1k views Asked by At

I am making a ruby gem with an executable and a class library. The executable has require "fpa/chklinks" which is the class library in lib/fpa directory.

I get the following error when I run my executable named chklinks.rb:

$ bin/chklinks.rb -h
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- fpa/chklinks (LoadError)
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from bin/chklinks.rb:7:in `<main>'

How can I make it find my library during development? I have tried require_relative "../lib/fpa/chklinks"

2

There are 2 answers

4
David Grayson On BEST ANSWER

Your gem should have a lib directory. During development, you will need to get that lib directory added to Ruby's load path one way or another.

You can add it in Ruby code. I wouldn't recommend doing that in your situation, but it is helpful to put something like this in your test helper or spec helper files to help your tests find the library:

$LOAD_PATH << 'lib'

You can add it with a Ruby command-line option or environment variable:

RUBYOPT="-Ilib" ruby bin/chklinks.rb
ruby -Ilib bin/checklinks.rb

I'm assuming the commands above would be run from the root directory of your gem, so the path you need to add is simply lib. If your setup is different, you would change lib in the commands above to be some other path.

1
ajnabi On

I fixed the problem by adding the following to my executable above my require statements:

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

or

As per David Grayson's post $LOAD_PATH << 'lib'

While this did the trick. Is there a better place for it, as I assume I will have to comment out this line before production?

Thanks