Created
April 21, 2018 02:55
-
-
Save tonytonyjan/81a85fe995a9f6287e7189488b86c746 to your computer and use it in GitHub Desktop.
Autoloader loads ruby files lazily
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
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 |
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
# 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