1

I have a file structure like

root
|--lib
   |--root.rb
   |--extensions
      |--strings.rb

I want to be able to use methods in string.rb in root.rb file.

So I added require 'extensions/strings' at the top of root.rb file.

But I get LoadError: cannot load such file -- extensions/strings.rb error.

How do I avoid this?

Jason Kim
  • 18,102
  • 13
  • 66
  • 105

4 Answers4

2

You can try the below:

require File.dirname(__FILE__) + "/extensions/strings"
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
Rajuk
  • 155
  • 8
  • getting this. `LoadError: cannot load such file -- /Users/jasonkim/.rvm/gems/ruby-1.9.3-p0/gems/rhapsody-0.0.1/lib/extensions/strings` – Jason Kim Apr 06 '13 at 20:48
2

Use require_relative if you are in Ruby 1.9 or later. In root.rb, write:

require_relative 'extensions/strings.rb'
David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • getting this. `LoadError: cannot load such file -- /Users/jasonkim/.rvm/gems/ruby-1.9.3-p0/gems/rhapsody-0.0.1/lib/extensions/strings.rb` – Jason Kim Apr 06 '13 at 20:48
  • 1
    require_relative definitely works, so if it isn't working for you then I need a lot more information. What file did you put the statement in? What is the full path to that file? What is the full path to strings.rb? Once you start asking the right questions, this stuff is not hard to figure out. – David Grayson Apr 06 '13 at 21:23
  • Thanks. All the answers were right. The detail I forgot to mention was that I was trying to load the file as a gem. – Jason Kim Apr 06 '13 at 21:26
1

I found the answer I am looking for here.

I used jandot's solution.

Dir[File.dirname(__FILE__) + '/extensions/*.rb'].each {|file| require file }


Edit after some testing,

For some reason, this doesn't throw any error message, but it doesn't seem to be loading the actual Ruby file.

I tried adding this to extensions/strings.rb

class Dog
  def self.bark
    puts "bark"
  end
end

And ran it on irb.

1.9.3-p0 :001 > require 'rhapsody'
 => true 
1.9.3-p0 :002 > Dog
NameError: uninitialized constant Dog
    from (irb):2
    from /Users/jasonkim/.rvm/rubies/ruby-1.9.3-p0/bin/irb:16:in `<main>'

So it's not finding the Dog class in extensions/strings.rb for some reason.


Edit after reading a guid in rubygems.org

When I start irb, I had to go irb -Ilib -rextensions

The guide explains the situation this way

We need to use a strange command line flag here: -Ilib. Usually RubyGems includes the lib directory for you, so end users don’t need to worry about configuring their load paths. However, if you’re running the code outside of RubyGems, you have to configure things yourself.

Community
  • 1
  • 1
Jason Kim
  • 18,102
  • 13
  • 66
  • 105
0
require_relative '../lib/extensions/strings'

Works for me.

hansottowirtz
  • 664
  • 1
  • 6
  • 16