What does `if __FILE__ == $0` mean in Ruby
Solution 1:
# Only run the following code when this file is the main file being run
# instead of having been required or loaded by another file
if __FILE__==$0
# Find the parent directory of this file and add it to the front
# of the list of locations to look in when using require
$:.unshift File.expand_path("../../", __FILE__)
end
Note that this particular practice (adding to the LOAD_PATH directory) is not usually necessary with the advent of require_relative
, and expand_path
is a simpler way of finding the parent directory.
Solution 2:
It's a couple of Ruby Mini-Design-Patterns
It means:
- IF the file is being executed directly, i.e., as a script,
- THEN find the directory the script is in and prepend it to beginning of the load/require search path
The conditional part can be useful for many things. A Ruby file could be written to provide functionality for a large program but also be available (with the extra code) as a script. Alternatively, the script-form could run the module's tests, while the component form implements some class for a bigger program and calls the tests only if referenced by name.
The path prepend has some general uses, besides the obvious one of finding private includes. If you have several different versions or releases of something, this way any companion "executables" (scripts) will get called preferentially. /usr/local/release232/bin/whatever will run everything from the same bin directory, even if release220 is earlier on the default path.