Ruby: How to "Require" a File from the Current Working Dir

Ruby: how to require a file from the current working dir?

In ruby 1.9.x, you can use the method require_relative. See http://www.ruby-doc.org/core-1.9.3/Kernel.html#method-i-require_relative.

Best way to require all files from a directory in ruby?

How about:

Dir["/path/to/directory/*.rb"].each {|file| require file }

require_relative from present working dir

File.expand_path('../', __FILE__)

gives you the path to the current directory. Thus if you have a file in bin/foo and you want to require something in lib/foo/settings.rb simply use

require File.join(File.expand_path('../../'), __FILE__), 'lib/foo/settings.rb')

Note the double ../ because the first is required to strip out from __FILE__ the current filename.

If the file is in /home/usr/admin/sources/myproject1/bin/foo

File.expand_path('../', __FILE__)
# => /home/usr/admin/sources/myproject1/bin
File.expand_path('../../', __FILE__)
# => /home/usr/admin/sources/myproject1
File.join(File.expand_path('../../', __FILE__), 'lib/foo/settings.rb')
# => /home/usr/admin/sources/myproject1/lib/foo/settings.rb

If you want to include the file with a relative path from the working directory, use

require File.join(Dir.pwd, 'settings.rb')

However, I don't think it's a good idea to hard-code a path in this way. You may probably want to pass the settings as argument to the command line.

It doesn't really make sense to create a gem that depends on a path of a file hard-coded on your machine.

Cleanest/One-liner way to require all files in directory in Ruby?

project_root = File.dirname(File.absolute_path(__FILE__))
Dir.glob(project_root + '/helpers/*') {|file| require file}

Or to golf it a bit more:

Dir.glob(project_root + '/helpers/*', &method(:require))

Get the file path based on the current working directory?

You should be able to just do something like follows.

absolute_path.split(Dir.pwd.to_s)[1].sub('/','')

This gets a 2 element array where the second element is the remaining portion of the path you want. The sub then strips off the prefixing forward slash.

Load File from parent directory

This is what I've done instead:

File.expand_path("../../neededsript.rb",File.dirname(__FILE__))


Related Topics



Leave a reply



Submit