Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby require_relative gives LoadError: cannot infer basepath inside IRB

Tags:

I am currently in

Dropbox/96_2013/work/ror/dmc/dmStaffing/QA/selenium_server_wyatt/spec/2day/units/

I can go into irb and require a file but it's a really long require...

require '/home/durrantm/Dropbox/96_2013/work/ror/dmc/dmStaffing/QA/selenium_server_wyatt/spec/2day/units/login_as_admin_spec.rb'
=> true

I want to use require_relative, as in

$ cd /home/durrantm/Dropbox/96_2013/work/ror/dmc/dmStaffing/QA/selenium_server_wyatt/spec/2day/
$ pwd
/home/durrantm/Dropbox/96_2013/work/ror/dmc/dmStaffing/QA/selenium_server_wyatt/spec/2day
$ irb
irb(main):001:0> require_relative 'units/login_as_admin_spec.rb' 

but I get:

LoadError: cannot infer basepath
like image 347
Michael Durrant Avatar asked May 07 '13 14:05

Michael Durrant


4 Answers

require_relative requires a file relative to the file the call to require_relative is in. Your call to require_relative isn't in any file, it's in the interactive interpreter, therefore it doesn't work.

You can use the long form of require by explicitly passing the full path:

require './units/login_as_admin_spec.rb'

Or you add the current directory to the $LOAD_PATH and just require as usual:

$LOAD_PATH << '.'
require 'units/login_as_admin_spec'
like image 148
Jörg W Mittag Avatar answered Sep 23 '22 05:09

Jörg W Mittag


This is a known bug in ruby:

  • Ruby bug #4487: require_relative fails in an eval'ed file

If you are using Pry, instead of IRB, this can be fixed by installing the pry-require_relative gem.

gem install pry-require_relative
like image 42
Gawin Avatar answered Sep 25 '22 05:09

Gawin


This worked:

require File.expand_path("../login_as_admin_spec.rb", __FILE__)
like image 41
Michael Durrant Avatar answered Sep 23 '22 05:09

Michael Durrant


require_relative works in the context of the current source file. This is different than the current working directory. I don't believe irb or pry have an understanding of "this current source file" concept; since you're not actually in a file.

In these REPLs, just use a relative path reference require './units/login_as_admin_spec.rb'.

like image 36
Aaron K Avatar answered Sep 22 '22 05:09

Aaron K