-
-
Save teohm/8679812 to your computer and use it in GitHub Desktop.
unload/reload
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
# Goal: put a non-Rails-aware Ruby library using normal `require`s in | |
# lib/mything. Have it transparently reloaded between requests like Rails app | |
# code is. | |
# | |
# The code here goes inside of your configure block in | |
# config/environments/development.rb. There are two parts, commented inline. | |
# Disable reload_classes_only_on_change. This makes Rails invoke the reloader | |
# even if no source files are changed. This is necessary because the autoloader | |
# and reloader don't know about our library, so they won't know to trigger a | |
# reload when they change. This will probably become slow for very large apps; | |
# on my (currently very small) app it costs about 85 ms in total request time. | |
config.reload_classes_only_on_change = false | |
# Manually unload and reload the library before every request. If it has global | |
# state, this will almost certainly fall over in terrible ways. If it defines | |
# constants other than the one ("Sim") explicitly dealt with here, you may | |
# actually die in real life. This assumes that there's a lib/sim.rb loading | |
# files from lib/sim/. | |
ActionDispatch::Reloader.to_prepare do | |
# If the library's top level module is currently loaded, unload it | |
if Object.const_defined?(:Sim) | |
Object.send(:remove_const, :Sim) | |
end | |
# Instruct ruby to "unrequire" all of the gems files. | |
# CAREFUL: make sure this only matches your library's files. | |
sim_base = File.expand_path(File.join(File.dirname(__FILE__), '../../lib/sim')) | |
$".delete_if do |s| | |
is_in_sim_dir = s.start_with?(sim_base + "/") | |
is_sim_file = s == sim_base + ".rb" | |
is_in_sim_dir || is_sim_file | |
end | |
# Re-require your library | |
# Note: because we removed all files previously required they will be reloaded | |
# even if you didn't use load/autoload in your gem. | |
require_relative "../../lib/sim" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment