Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest/One-liner way to require all files in directory in Ruby?

Tags:

ruby

require

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?

like image 888
Lance Avatar asked Mar 21 '10 19:03

Lance


People also ask

What does __ file __ mean in Ruby?

__FILE__ is the filename with extension of the file containing the code being executed. In foo. rb , __FILE__ would be "foo. rb".

What is require relative in Ruby?

The require_relative method accepts a relative file path to the file we want to require. This means we're providing a file path that starts from the file in which the require_relative statement is called. require_relative '../lib/ruby_file.rb'

How to make directory in Ruby?

Using Ruby's Mkdir Method To Create A New Directory If you want to create a new folder with Ruby you can use the Dir. mkdir method. If given a relative path, this directory is created under the current path ( Dir. pwd ).

How does require work in Ruby?

In Ruby, the require method is used to load another file and execute all its statements. This serves to import all class and method definitions in the file.


2 Answers

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))
like image 80
sepp2k Avatar answered Oct 21 '22 09:10

sepp2k


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]

like image 3
pedz Avatar answered Oct 21 '22 10:10

pedz