shin
shin

Reputation: 32721

Confusion about require, require_relative, include in Ruby

Please correct me if anything below is wrong.

  1. My understanding is that I can use require 'gemname' in spec_helper.rb

  2. Can I use require without any path for files in lib directory in spec_helper.rb ?

  3. I never use require_relative in spec.helper.rb.

  4. I need to use require, require_relative in lib/myfile.rb

Q. When do I need to use include in lib/myfile.rb ?

Update

Sample structure

.
./ChangeLog.rdoc
./data
./data/msdata2013.xls
./data/msdataparts.xls
./Gemfile
./Gemfile.lock
./lib
./lib/correlation.rb
./lib/Irtest.rb
./lib/subcorrelation
./lib/subcorrelation/subjects.rb
./lib/subcorrelation/version.rb
./lib/subcorrelation.rb
./LICENSE.txt
./Rakefile
./README.rdoc
./spec
./spec/spec_helper.rb
./spec/subcorrelation_spec.rb
./subcorrelation.gemspec

Upvotes: 2

Views: 2554

Answers (2)

sam
sam

Reputation: 163

Generally you will use require for gems in this situation, these should not need a path.

require_relative will require a path in your situation and should be placed in whatever file you need to use another file in. (if you're writing tests, the files with the things you are testing need to be listed via require_relative in the test file)

Include (and extend) pertain to modules and as far as I can tell for what you're doing you don't need them.

Upvotes: 0

bjhaid
bjhaid

Reputation: 9762

  1. Yes you can require a gem in spec_helper.rb
  2. Depends on you lib directory structure, if it is flat, you don't need to specify paths rspec looks in the lib directory by default
  3. Require relative would only search for files relative to the spec_helper.rb, which might not be right as it rspec looks up files in the lib directory
  4. You might need to lookup docs on require and require_relative

include is used to include Modules in ruby

Upvotes: 2

Related Questions