How to import classes from another package

0

How do I import a class that is in another package Example: "model" package contains the "Car" class, package "execution" contains the "Main" class, from inside the "Main" I want to import the "Car" class, How do I do this? I used require_relative "Carro" , but only worked when they were in the same package

    
asked by anonymous 24.09.2018 / 06:50

1 answer

1

Ruby does not work with packages, but rather files. The methods that control this are Kernel#require and Kernel#require_relative .

Kernel#require always asks for absolute paths to the file path, while Kernel#require_relative accepts relative paths.

See the example:

.
├── init.rb
└── modules
    ├── module_1.rb
    └── module_2.rb

The files:

# ./init.rb
puts 'init.rb called'
require './modules/module_1'

# ./modules/module_1.rb
puts 'module 1 called'
require_relative 'module_2'

# ./modules/module_2.rb
puts 'module 2 called'

Note that from init.rb , in the root, to module_1.rb , I used Kernel#require with an absolute path, using ./modules/module_1 .

Now from module_1 to module_2 , because they are in the same folder, I could use Kernel#require_relative .

The result is:

$ ruby ./init.rb
init.rb called
module 1 called
module 2 called

If you want to go back one level in the folder hierarchy, just use ../ , ../../ , and so on ...

    
03.10.2018 / 06:14