Skip to content

Instantly share code, notes, and snippets.

@davidlee
Created May 27, 2010 00:56
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/415285 to your computer and use it in GitHub Desktop.
Save davidlee/415285 to your computer and use it in GitHub Desktop.
Simple DRY autoloading
# 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