How to Import Classes from Another Package

Asked

Viewed 184 times

0

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

1 answer

1


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

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

Take the example:

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

The archives:

# ./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'

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

Of the module_1 to the module_2, by being in the same folder, I was able to use the 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 the ../, ../../ and so on...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.