问题
I'm new to ruby, but I'm working on my first ruby program. It currently has two files, one is a library of functions (xgync.rb
stored in lib
) the other is the executable xgync
stored in 'bin'. (Project visible here https://bitbucket.org/jeffreycwitt/xgync/src) I've also created a symlink to my /usr/local/bin/xgync
so that I can write the command xgync {arguments}
from anywhere in the terminal.
The problem seems to be that bin/xgync
depends on the library lib/xgync.rb
. I've written this dependency in bin/xgync
as follows:
$:.unshift(File.dirname(__FILE__) + '/../lib')
require "xgync"
However, i keep getting the following error:
/Users/JCWitt/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- xgync (LoadError)
from /Users/JCWitt/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /usr/local/bin/xgync:4:in `<main>'
can you see anything wrong with what I've written? Could the symlink be somehow messing things up?
Thanks for your help :)
回答1:
When using ruby 1.9.x you don't usually alter the path with the $:.unshift
when requiring other files in your project.
Instead the best practice is to use require_relative
instead.
require_relative '../lib/xgync.rb'
require_relative
requires files relative to the file you are currently editing.
But the error you experience appears, because you require a file, which does not exist:
- bin/xgync
- lib/xgync.rb
These are the files in your project according to your question, and the code-excerpt is from bin/xgync you extended the path to look for files in lib/ but you try to require 'xgync'
which is a file, that is not present in lib/, so if you wanted to use this method (instead of require_relative
you would have to use require 'xgync.rb'
.
来源:https://stackoverflow.com/questions/11600170/ruby-require-not-working