How to import without specifing path in ruby

偶尔善良 提交于 2021-02-05 11:36:32

问题


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:

  1. They load a pre-installed gem, and since the gem home path is part of the $LOAD_PATH, it can be found and loaded.
  2. The code you see is a part of a gem, and it loads one of its own files.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!