views:

337

answers:

2

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?

+5  A: 
Dir.glob(File.dirname(__FILE__) + '/helpers/*') {|file| require file}

Or to golf it a bit more:

Dir.glob(File.dirname(__FILE__) + '/helpers/*', &method(:require))
sepp2k
yeah, that's sick. thanks man.
viatropos
I wouldn't have thought about method#to_proc, nice!
severin
A: 

To me :

Dir.glob(File.dirname(FILE) + '/helpers/*') {|file| require file}

OR

Dir.glob(File.dirname(FILE) + '/helpers/*', &method(:require))

Neither are working. I think in my case, its because of order in which file is loaded. I have a class(say Class A) which is inherited from other class(say Class B). Both of them are inside module named MyModule. It gives me error as

uninitialized constant MyModule::B (NameError)

Any help??

Shyamkkhadka