Ruby: Require everything in a directory

03 July 2007 Recently I've been working a lot with the Liquid templating system and in our application initialisation we needed to quickly require all the files in a particular directory that aren't in the normal rails load path. Normally a good way to do this is to just add the new paths onto your Rails load path


$LOAD_PATH << File.join(File.dirname(__FILE__), '../app/drops')

or, in environment.rb

config.load_paths += %W( #{RAILS_ROOT}/app/drops #{RAILS_ROOT}/app/filters )

This particular app uses engines so most of the configuration resides in our core plugin in order not to dirty up environment.rb and make is easier to keep all the configuration centrally managed. This means we can't really touch environment.rb or anything in the Rails initializer block for that matter.
Then I discovered the power of .glob


Dir.glob(File.join(File.dirname(__FILE__), '../app/drops/*.rb')).each {|f| require f }

Perfect.

Edited: Yes - that second snippet of code is from Mephisto - at the moment it's the best reference for how to implement a liquid based templating system. Thanks Rick, you've really helped us out!

Comments

Sorry, comments are closed for this article.