Skip to content

Instantly share code, notes, and snippets.

@garybernhardt
Last active January 4, 2016 21:09
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save garybernhardt/8678679 to your computer and use it in GitHub Desktop.
Save garybernhardt/8678679 to your computer and use it in GitHub Desktop.
# Goal: put a non-Rails-aware Ruby library using normal `require`s in
# lib/sim. 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.
# Reload code whenever the simulator changes.
config.watchable_dirs["lib/sim"] = [:rb]
config.watchable_files << "lib/sim.rb"
# Manually unload and reload the simulator before every request. 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 simulator's 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 library.
require_relative "../../lib/sim"
end
@ClayShentrup
Copy link

But Gary,

>class Foo
* def bar
* puts 'bar'
* end
* end
=> nil
> class Moo < Foo
* end
=> nil
> Object.send(:remove_const, :Foo)
=> Foo
> Moo.new.bar
bar

Doh!

@dalizard
Copy link

@BrokenLadder What is the idea behind your comment?

@stevenharman
Copy link

I think @BrokenLadder is saying that objects which inherit from your lib might not act as expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment