Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load File from parent directory

I'm working with Ruby 1.8 and I have script that I want to call but it's in a parent folder. Below is the structure:

maindir/
neededscript.rb
  subdir/
    subdir2/
      myscript.rb

How can I require neededscript.rb from inside myscript.rb?

like image 884
zulqarnain Avatar asked May 30 '13 10:05

zulqarnain


People also ask

How do I go to parent directory path?

To change directories using absolute pathnames, type cd /directory/directory; to change directories using relative pathnames, type cd directory to move one directory below, cd directory/directory to move two directories below, etc.; to jump from anywhere on the filesystem to your login directory, type cd; to change to ...

What is a parent directory in files?

Directory: A named group of files (a folder); a directory that contains more folders (subdirectories) are called the "parent" and the folder within it is referred to as the "child" of that directory..

How do I open a file in a different directory in Python?

How do I open a file in a different directory in Python? Use open() to open a file in a different directory Join path with filename into a path to filename from the current directory. Call open(file) with file as the resultant path to filename to open filename from the current directory.


3 Answers

In Ruby >=1.9 you can use the require_relative method

require_relative complements the builtin method require by allowing you to load a file that is relative to the file containing the require_relative statement.

require_relative '../../neededscript.rb'
like image 70
fullybaked Avatar answered Nov 16 '22 00:11

fullybaked


You can also add the path to the ruby libs path by adding these lines to myscript.rb before doing the require

binpath = File.dirname( __FILE__ )
$:.unshift File.expand_path( File.join( binpath, ".." ) )
like image 21
sethi Avatar answered Nov 16 '22 01:11

sethi


This is what I've done instead:

File.expand_path("../../neededsript.rb",File.dirname(__FILE__))
like image 40
zulqarnain Avatar answered Nov 16 '22 01:11

zulqarnain