How to import without specifing path in ruby

前端 未结 1 1569
遥遥无期
遥遥无期 2021-01-27 16:53

When I develop ruby app.

I found that some apps import other modules without specifying specific path like following

require \'test\'

I always

相关标签:
1条回答
  • 2021-01-27 17:26

    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.

    0 讨论(0)
提交回复
热议问题