PepperoniPizza
PepperoniPizza

Reputation: 9102

Ruby require module/class on another folder

I am new to Ruby and I'm trying to understand a good way to require modules or classes defines elsewhere. I have this setup:

test/
  database/
    base.rb
  scripts/
    run.rb

base.rb

module A
  def hi
    puts "It works"
  end
end

run.rb

# I don't know how to require module A here
hi()

Now I know I can do something like: require "#{File.dirname(__FILE__)}/database/base" but that looks fragile. I want to know if there is a way to add a folder to the LOAD_PATH of a particular folder or the whole application.

Upvotes: 6

Views: 6600

Answers (2)

Shiva
Shiva

Reputation: 12514

It depends on from which file you are requiring other ruby file. Its relative to the host file.
In you situation

test/
  database/
    base.rb
  scripts/
    run.rb

I suppose you are tying to require the base.rb from run.rb then do this

require '../database/base.rb'
class SomeClass
  include A
  def some_method
    hi()
  end
end

Upvotes: 1

philip yoo
philip yoo

Reputation: 2512

I believe the following will work:

require_relative '../database/base'

Inside run.rb file, include A and then run file

Upvotes: 11

Related Questions