Ruby: how to “require” a file from the current working dir?

…衆ロ難τιáo~ 提交于 2019-11-29 06:17:49

问题


How do I require a file from the current folder?

I have a file called sql_parser.rb that contains a class. I want to include this in another file also in the same folder, so I used:

require 'sql_parser'

That fails when I run from that folder:

LoadError: no such file to load -- sql_parser

I tried using IRB in the folder where this file exists and requiring it from there, but had the same issue.


回答1:


In ruby 1.9.x, you can use the method require_relative. See http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-require_relative.




回答2:


Use

$:.unshift File.join(File.dirname(__FILE__))

to ensure that you're getting a path based on where the script is located, rather than where the program is being executed from. Otherwise, you're throwing away the security benefit gained by removing "." from the load path.

(Yes, the title of the question talks about requiring a file in the directory the script is being run from, but the body of the question mentions that the required file is in the same folder as the script in question)




回答3:


also...

require "./myRubyFile" # notice we exclude the .rb from myRubyFile.rb




回答4:


On 1.9 the syntax changed to require_relative, as the other answers to this question said.

If you are writing in Ruby 1.8, I suggest writing your code in a forward looking manner, and using the require_relative gem, so you can use this keyword in your Ruby 1.8 and deal with one less transitional thing when you move to 1.9




回答5:


$LOAD_PATH << Dir.pwd
require 'sql_parser'

As noted by @AndrewGrimm, due to security reasons, you should use this instead:

$LOAD_PATH << File.join(File.dirname(__FILE__))
require 'sql_parser'

Your directory has to be in the current load path. The load path is stored in a global array called $LOAD_PATH. If you append your current directory to it, then you can use require to load any files within the directory.

Using Dir.pwd instead of pwd.chomp as suggested by the Tin Man

Also I prefer this over require_relative unless you have a really small project otherwise things can get ugly.



来源:https://stackoverflow.com/questions/8510981/ruby-how-to-require-a-file-from-the-current-working-dir

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