Created
May 27, 2010 00:56
-
-
Save davidlee/415285 to your computer and use it in GitHub Desktop.
Simple DRY autoloading
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
# simple, DRY autoloading | |
require 'active_support' | |
class Module | |
def const_missing_with_mojo mod | |
# HACK ALERT eject if activesupport voodoo is interfering | |
targ = caller.reject {|x| x =~ /active_?support/ }[0].split(':').first | |
autoload_path targ | |
if const_defined? mod | |
const_get mod | |
else | |
const_missing_without_mojo mod | |
end | |
end | |
alias_method_chain :const_missing, :mojo | |
end | |
class Object | |
def autoload_path path=caller.first.gsub(/:\d+$/,'') | |
path = File.expand_path path.gsub(/\.rb/, '') | |
Dir["#{path}/*.rb"].each do |fn| | |
const = File.split(fn).last.gsub(/\.rb$/,'').classify | |
autoload const, fn | |
end | |
end | |
alias_method :autoloads, :autoload_path | |
end | |
# init.rb: | |
# must call this manually since init.rb doesn't match the folder 'lib' | |
autoload_path 'lib' | |
puts MyLib | |
# lib/mylib.rb: | |
module Mylib | |
puts Submodule | |
end | |
# lib/mylib/submodule.rb | |
module Mylib | |
class Submodule | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment