Skip to content

Instantly share code, notes, and snippets.

@davidlee
Created October 20, 2010 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidlee/637603 to your computer and use it in GitHub Desktop.
Save davidlee/637603 to your computer and use it in GitHub Desktop.
autoloads.rb
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