1

I need to require a folder with a lot of files:

require './models/request_builders/ipg_request_builder.rb'
require './models/request_builders/omnipay_request_builder.rb'
require './models/request_builders/girogate_request_builder.rb'

How I can require the entire folder?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

1 Answers1

1

Short answer :

Dir['/path/*.rb'].each { |file| require file }

Explanation :

Dir[] is an equivalent of calling Dir.glob() which take a pattern string and returns an array containing the matching filenames. (cf. more detail about patterns https://ruby-doc.org/core-3.1.1/Dir.html#glob-method)

Exemple with a given directory myDirectory at filesystem root containing only file1.rb and file2.rb, Dir['/myDirectory/*.rb'] will return :

[
  '/myDirectory/file1.rb',
  '/myDirectory/file2.rb'
]

Knowing how Dir.glob works, we just need to iterate on the list of files by passing their names in the require method :

Dir['/myDirectory/*.rb'].each { |file_name| require file_name }
D1ceWard
  • 972
  • 8
  • 17
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Nic3500 Sep 21 '18 at 12:57