22

When creating gems, I often have a directory structure like this:

|--lib
    |-- helpers.rb
    `-- helpers
        |-- helper_a.rb
        `-- helper_b.rb

Inside the helpers.rb, I'm just require-ing the files in the helpers directory. But I have to do things like this:

$:.push(File.dirname(__FILE__) + '/helpers')
require 'helper_a'
require 'helper_b'

Is there a way to make that one line so I never have to add to it? I just came up with this real quick:

dir = File.join(File.dirname(__FILE__), "helpers")
Dir.entries(dir)[2..-1].each { |file| require "#{dir}/#{file[0..-4]}" }

But it's two lines and ugly. What slick tricks have you done to make this a one liner?

Lance
  • 75,200
  • 93
  • 289
  • 503
  • 1
    Duplicate of http://stackoverflow.com/questions/735073/best-way-to-require-all-files-from-a-directory-in-ruby - use `Dir["/path/to/directory/*.rb"].each {|file| require file }` – Marcel Jackwerth Mar 21 '10 at 19:13
  • Even nicer, use the require_all gem mentioned in that question. – clacke Jun 09 '11 at 08:36

4 Answers4

57
project_root = File.dirname(File.absolute_path(__FILE__))
Dir.glob(project_root + '/helpers/*') {|file| require file}

Or to golf it a bit more:

Dir.glob(project_root + '/helpers/*', &method(:require))
sepp2k
  • 363,768
  • 54
  • 674
  • 675
3

I like require_relative:

Dir.glob('lib/**/*.rb') { |f| require_relative f }

The `&method(:require_relative) trick won't work with require_relative. I get:

`require_relative': cannot infer basepath (LoadError)

But it does save the hassle of computing project_root

I'm using ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.5.0]

pedz
  • 2,271
  • 1
  • 17
  • 20
1
# helpers.rb
Dir[__dir__ + '/helpers/*'].each &method(:require)
Lev Lukomsky
  • 6,346
  • 4
  • 34
  • 24
0

Hi the cleanest way I have discovered is to use Dir.glob with wild cards.

Put the following in your rakefile:

gem.files = Dir.glob('lib/**/ *.rb')

It should work a treat.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
WebDevMonk
  • 11
  • 2