0

I'm building a web app in Sinatra and I have a bunch of files in /lib/checkers/

I'm currently requiring them by doing this:

require File.expand_path(File.dirname(__FILE__) + '/lib/checkers/board.rb')
require File.expand_path(File.dirname(__FILE__) + '/lib/checkers/checker.rb')

which seems dumb but I have tried

require '/lib/checkers'

or

require '/lib/checkers/' 

or

require File.expand_path(File.dirname(__FILE__) + 'lib/checkers/')

and other variants along the same them but nothing seems to work. Can you help?

steve_gallagher
  • 3,778
  • 8
  • 33
  • 51

1 Answers1

4
require_relative 'lib/checkers/board'
require_relative 'lib/checkers/checker'

This is how I have always done it. This is located in my main app file, which is always in the root directory. I'm unsure how it will behave from other files, although I believe it will be relative to the calling file.

Also, settings.root will return the root directory of your app, no need for File.dirname(__FILE__) anywhere.

This works in Ruby 1.9 without any special techniques via the comments above.

If you are using 1.8, you can do this

require './lib/checkers/board'
require './lib/checkers/checker'

Other techniques for 1.8 are listed in this question.

Community
  • 1
  • 1
Paul Hoffer
  • 12,606
  • 6
  • 28
  • 37
  • Note that require_relative is only available in Ruby >= 1.9.2. See [this post](http://stackoverflow.com/questions/4333286/ruby-require-vs-require-relative-best-practice-to-workaround-running-in-both) for more info if you choose to go with this solution. – user2398029 Feb 27 '12 at 03:45
  • @louism thanks for reminding me. I started learning Ruby with 1.9, so I tend to forget issues in 1.8. – Paul Hoffer Feb 27 '12 at 04:05