Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way to require a file in the same directory in ruby?

Tags:

path

ruby

require

Is there a shorter way to require a file located in the same directory (as the script being executed)?

require File.expand_path(File.dirname(__FILE__) + '/some_other_script') 

I read that require "my_script" and require "./my_script" will actually load the script twice (ruby will not recognize that it is actually the same script), and this is the reason why File.expand_path is recommended: if it is used every time the script is required, then it will only be loaded once.

It seems weird to me that a concise language like Ruby does not seem to have a shorter solution. For example, python simply has this:

import .some_other_module_in_the_same_directory 

I guess I could monkey-patch require... but that's just evil! ;-)

like image 997
MiniQuark Avatar asked Apr 25 '09 08:04

MiniQuark


People also ask

What does __ file __ mean in Ruby?

The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.

How do I use require in Ruby?

The require method takes the name of the file to require, as a string, as a single argument. This can either be a path to the file, such as ./lib/some_library. rb or a shortened name, such as some_library. If the argument is a path and complete filename, the require method will look there for the file.

What is require relative in Ruby?

require_relative allows you to "load a file that is relative to the file containing the require_relative statement". With require , ./ indicates a path that is relative to your current working directory. – Ajedi32.

How do I change the path of a file in Ruby?

Ruby has a method for this case. It is File::expand_path . Converts a pathname to an absolute pathname. Relative paths are referenced from the current working directory of the process unless dir_string is given, in which case it will be used as the starting point.


2 Answers

Since ruby 1.9 you can use require_relative.

Check the latest doc for require_relative or another version of the Core API.

like image 70
knut Avatar answered Sep 18 '22 15:09

knut


Just require filename.

Yes, it will import it twice if you specify it as filename and ./filename, so don't do that. You're not specifying the .rb, so don't specify the path. I usually put the bulk of my application logic into a file in lib, and then have a script in bin that looks something like this:

#!/usr/bin/env ruby  $: << File.join(File.dirname(__FILE__), "/../lib") require 'app.rb' App.new.run(ARGV) 

Another advantage is that I find it easier to do unit testing if the loading the application logic doesn't automatically start executing it.

like image 29
dvorak Avatar answered Sep 18 '22 15:09

dvorak