Created
October 20, 2010 23:51
-
-
Save davidlee/637603 to your computer and use it in GitHub Desktop.
autoloads.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
begin | |
require 'term/ansicolor' | |
rescue LoadError | |
end | |
module Kernel | |
def autoloads(lib_dir) | |
base_dir = File.expand_path File.join(Rails.root, lib_dir) | |
dir_glob = File.join(base_dir, '**/') | |
Dir[dir_glob].sort_by(&:length).reverse.each do |dir| | |
constant_names = dir.gsub(File.dirname(base_dir), ''). | |
gsub(/(^\/|\/$)/, ''). | |
titlecase. | |
gsub(' ',''). | |
split('/') | |
mod = constant_names.inject(Object) do |const, name| | |
if const.const_defined?(name) | |
const.const_get(name) | |
else | |
const.const_set(name, Module.new) | |
end | |
end # inject | |
Dir[File.join dir, "*.rb"].each do |fn| | |
const_name = File.basename(fn).gsub(/\.rb$/,'').titlecase.gsub(' ','').to_sym | |
# UNCOMMENT FOR DEBUG INFO: | |
# puts Term::ANSIColor.green("#{mod} -> autoload :#{const_name}, '#{fn}'") if defined?(Term::ANSIColor) | |
mod.autoload const_name, fn | |
end | |
end | |
end # self.load | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment