-2

I have two files person.rb and contact_info.rb and the person.rb file contains a class, and the contact_info.rb file contains a module. When i do load 'person.rb' in irb this works fine when load 'contact_info.rb' is at the top of this file.

When I switch this to require 'contact_info.rb' at the top of the person.rb file, and in irb do require 'person.rb' I get an error (i've included the error at the bottom of this text and it's using a completely different file path.

I've googled some solutions such as using './person.rb' and require_relative 'person' but these don't work either.

I've simplified the code within files to make things easier.

Any help would be awesome.

CODE IN THE person.rb FILE

require 'contact_info.rb'
  class Person
    include ContactInfo
  end

CODE IN THE contact_info.rb FILE

module  ContactInfo
  #some code
end

ERROR MESSAGE THAT I'M GETTING - when I type in require 'person.rb' in irb.

**note - when i drag the file into the command line the file path is /Volumes/New\ Passport/All\ Creative/Ruby/module_folder_tut/person.rb

LoadError: cannot load such file -- person.rb
  from /Users/paulknight/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/paulknight/.rvm/rubies/ruby-2.4.1/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from (irb):1
from /Users/paulknight/.rvm/rubies/ruby-2.4.1/bin/irb:11:in `<main>'
pjk_ok
  • 618
  • 7
  • 35
  • 90

1 Answers1

1

Current directory in NOT on the ruby search path by default. Add it to $: and everything will be fine (assuming you are launching irb from the directory where person.rb is located):

$: << "."
require "person.rb"

More detailed info.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • 2
    Though `require_relative 'contact_info'` and `require_relative 'person'` should work. – radubogdan Nov 09 '17 at 13:41
  • 1
    @radubogdan yes, indeed, thanks, I will update the answer saying to start irb from the respective directory. – Aleksei Matiushkin Nov 09 '17 at 13:42
  • Hi Mudasobwa, adding $: << "." did work. Is there anyway I can make this the default behaviour instead of having to add each time i open irb? – pjk_ok Nov 09 '17 at 15:13
  • sorry I forget the @ symbol in the above comment @mudasobwa – pjk_ok Nov 09 '17 at 15:36
  • No, please do not do this. And please do not advocate this. It is a *huge* security risk, and allows basically anybody who can get you to execute that script with a directory of their choosing as your working directory (which is quite easy to achieve) to **execute arbitrary code as you**. – Jörg W Mittag Nov 09 '17 at 15:53
  • @JörgWMittag I have advocated to do that from `irb`. If anybody could force me to execute `irb` I am way more vulnerable already. – Aleksei Matiushkin Nov 09 '17 at 16:02