Skip to content

Instantly share code, notes, and snippets.

@tonytonyjan
Created April 21, 2018 02:55
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 tonytonyjan/81a85fe995a9f6287e7189488b86c746 to your computer and use it in GitHub Desktop.
Save tonytonyjan/81a85fe995a9f6287e7189488b86c746 to your computer and use it in GitHub Desktop.
Autoloader loads ruby files lazily
module AutoLoader
def self.included(mod)
caller_path, = caller(1..1).first.partition(':')
pattern = "#{File.dirname(caller_path)}/#{File.basename(caller_path, '.rb')}/*.rb"
Dir.glob(pattern).each do |path|
class_name = ::Utils.classify(File.basename(path, '.rb')).to_sym
mod.autoload class_name, path
end
end
end
# foo.rb
module Foo
include Autoloader
end
# foo/bar.rb
module Foo
class Bar
end
end
# foo/buz.rb
module Foo
class Buz
end
end
# main.rb
require 'foo'
Foo::Bar.new # autoload foo/bar.rb
Foo::Buz.new # autoload foo/buz.rb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment