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! ;-)
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.
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.
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.
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.
Since ruby 1.9 you can use require_relative
.
Check the latest doc for require_relative
or another version of the Core API.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With