Skip to content

Instantly share code, notes, and snippets.

@mvastola
Created August 31, 2021 22:07
Show Gist options
  • Save mvastola/0eeb017beb5dee4a1509a5628c14c4d4 to your computer and use it in GitHub Desktop.
Save mvastola/0eeb017beb5dee4a1509a5628c14c4d4 to your computer and use it in GitHub Desktop.
#!/usr/bin/env rvm-shebang-ruby
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'zeitwerk'
gem 'byebug'
end
require 'pp'
require 'tmpdir'
require 'logger'
require 'pathname'
class ZeitwerkTester
attr_reader :order, :silent, :logger
def initialize(order:, silent: true)
@order = order
@silent = silent
@logger = Logger.new(@silent ? '/dev/null' : STDERR)
end
def parent_dir
@parent_dir ||= Pathname.new(Dir.mktmpdir)
end
def subdir
@subdir ||= (parent_dir / 'subdir').tap(&:mkpath)
end
def parent_dir_loader
@parent_dir_loader ||= Zeitwerk::Loader.new.tap do |loader|
loader.logger = logger
loader.log!
loader.ignore(subdir)
loader.push_dir(parent_dir)
loader.collapse(parent_dir)
loader.enable_reloading
loader.setup
loader.eager_load
end
end
def subdir_loader
@subdir_loader ||= Zeitwerk::Loader.new.tap do |loader|
loader.logger = logger
loader.log!
loader.push_dir(subdir)
loader.collapse(subdir)
loader.enable_reloading
loader.setup
loader.eager_load
end
end
def load!
puts "Now testing loading `parent_dir` and `subdir` in #{order} order:"
case order
when :normal
parent_dir_loader
subdir_loader
when :reverse
subdir_loader
parent_dir_loader
else
raise ArgumentError, 'Invalid argument'
end
rescue Zeitwerk::Error => ex
puts "An exception was raised by Zeitwerk while loading in #{order} order:"
pp ex unless silent
:failed
else
puts "Loading was successful in #{order} order."
:succeeded
end
def cleanup!
return unless parent_dir&.exist?
parent_dir.rmtree
true
end
def run!
load!
ensure
cleanup!
puts
end
class << self
def test!(silent:)
puts "Will test loading two dirs: `parent_dir` and `subdir` in both orders:"
puts
%i[normal reverse].map do |order|
[ order, new(order: order, silent: silent).run! ]
end.to_h
end
end
end
pp ZeitwerkTester.test!(silent: ARGV.first.nil?)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment