Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby require module/class on another folder

Tags:

ruby

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.

like image 890
PepperoniPizza Avatar asked Sep 05 '26 17:09

PepperoniPizza


2 Answers

I believe the following will work:

require_relative '../database/base'

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

like image 56
philip yoo Avatar answered Sep 07 '26 10:09

philip yoo


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
like image 31
illusionist Avatar answered Sep 07 '26 09:09

illusionist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!