问题
When I develop ruby app.
I found that some apps import other modules without specifying specific path like following
require 'test'
I always set some modules in certain directory and set following path.
require './sample/test'
How can I import without path ?
Are there any environment setting around this?
Am I missing important thing?
If someone has opinion,please let me know.
Thanks
回答1:
As was mentioned in the comments, Ruby looks at the $LOAD_PATH
global variable to know where to look for required libraries.
Normally, under most circumstances, you should not mess with it and just leave it as is.
When you see other libraries using require
without a leading dot for relative path (e.g., require 'sinatra'
), it usually means one of these:
- They load a pre-installed gem, and since the gem home path is part of the
$LOAD_PATH
, it can be found and loaded. - The code you see is a part of a gem, and it loads one of its own files.
- The code you see is a part of a larger framework (e.g., Rails), which has altered the
$LOAD_PATH
variable.
You can see all the folders available in the $LOAD_PATH
like this:
pp $LOAD_PATH
If, for some reason, you insist on altering the $LOAD_PATH
to load your own local files, you can do so like this:
$LOAD_PATH.unshift __dir__
require 'my-local-file'
Bottom line, my recommendation to you is: Do not use this technique just so that you require
statements "look nicer", and if you have functionality that can be encapsulated in a gem (private or public), do it.
来源:https://stackoverflow.com/questions/65626558/how-to-import-without-specifing-path-in-ruby