Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

require

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.

like image 874
Matt Roberts Avatar asked Dec 14 '11 20:12

Matt Roberts


2 Answers

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.

like image 59
tomferon Avatar answered Sep 17 '22 17:09

tomferon


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)

like image 33
Andrew Grimm Avatar answered Sep 19 '22 17:09

Andrew Grimm