Reputation: 2415
When attempting to place Ruby dependency files into a Ruby file, why is the "./" (dot + forward slash) necessary when typing out the file directory? Oddly enough it is only needed when using the require
keyword and not the load
keyword.
i.e.: module.rb (the dependency)
module SomeModule
def someMethod
puts "hello"
end
end
method.rb
require "./module.rb"
#require "module.rb" does not work
class Animal
include SomeModule
end
class Person
include SomeModule
end
animal = Animal.new
animal.someMethod
person = Person.new
person.someMethod
#irb --> need to also write require " ./method.rb" to call it
Upvotes: 0
Views: 814
Reputation: 2418
It is only needed when using the require keyword and not the load keyword. Why?
load
, require
and require_relative
are all methods which take a filename as an argument that is to be loaded. They need to locate the filename passed an an argument
load
load checks for the file in the LOAD PATH which can be accessed using the global variable $LOAD_PATH
or $:
Even though the current working directory (designated by .) is NOT actually in the LOAD_PATH, the load method acts as if it is so is able to locate a file without explicitly appending the current directory to the file name passed as an argument
require
require is similar to load with two main differences
The first is that it's unaware about the current working directory. It does not add it to the LOAD PATH so once ruby searches it, it doesn't find the file. This is why you have to explicitly tell ruby about the current working directory and how to locate the file from the current directory using ./path_to_file.
If you don't want to add ./, you have to add the current directory to your Load Path
$: << '.'
require 'module.rb'
This will work as the current directory is now in the load path which is where ruby will search for the file.
The second main difference is that when you make multiple calls to require in a file passing it the same filename as an argument, the file will be required only the first time. Ruby keeps track of the files required. However with multiple calls to load with the same filename as an argument, the file is always loaded.
require 'time' => true
require 'time' => false #second call within the same file
require_relative
require_relative searches relative to the file in which the method call was executed which is why you don't need to alter the LOAD PATH by explicitly adding the current working directory
Upvotes: 0
Reputation: 7308
If module.rb and method.rb are in the same directory, instead of using require
you should use require_relative
. Thus, the top of method.rb would look like this
require_relative 'module'
class Animal
Upvotes: 1