Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby require path

Tags:

ruby

require

I have a Ruby code with different classes in a few files. In one file, I start the execution. This file requires my other files.

  • Is this a good way to start a ruby code?
  • When I run the code from a symbolic link, for example DIR2/MyRubyCode is a link to the main file DIR1/MyRubyCode.rb, then my requires will fail. I solved the problem by adding the path DIR1 to $LOAD_PATH before the require, but I think there would be much better ways to do it. Do you have any suggestions about that?
like image 752
Cedric H. Avatar asked Aug 29 '10 10:08

Cedric H.


People also ask

Where does ruby look for require?

Ruby looks in all the paths specified in the $LOAD_PATH array.

How do I use require in Ruby?

The require method takes the name of the file to require, as a string, as a single argument. This can either be a path to the file, such as ./lib/some_library. rb or a shortened name, such as some_library. If the argument is a path and complete filename, the require method will look there for the file.

What is Ruby load path?

$LOAD_PATH is used for the exact same purpose. In ruby an identifier starting with a $ symbol is a global variable. $LOAD_PATH is an array of absolute paths i.e it stores the exact location of all the dependencies in the project.


2 Answers

If you're using Ruby 1.9 or greater, user require_relative for your dependencies.

require_relative 'foo_class'
require_relative 'bar_module'
like image 113
Alex V Avatar answered Nov 13 '22 22:11

Alex V


If you want to check if a Ruby file is being 'require'ed or executed with 'ruby MyRubyCode.rb', check the __FILE__ constant.

# If the first argument to `ruby` is this file.
if $0 == __FILE__
  # Execute some stuff.
end

As far as the require/$LOAD_PATH issue, you could always use the relative path in the require statement. For example:

# MyRubyCode.rb
require "#{File.dirname(__FILE__)}/foo_class"
require "#{File.dirname(__FILE__)}/bar_module"

Which would include the foo_class.rb and bar_module.rb files in the same directory as MyRubyCode.rb.

like image 42
Dale Campbell Avatar answered Nov 13 '22 23:11

Dale Campbell