Skip to content

Instantly share code, notes, and snippets.

@lazyatom
Created February 6, 2015 15:05
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 lazyatom/547a1cca0f3d90b1338f to your computer and use it in GitHub Desktop.
Save lazyatom/547a1cca0f3d90b1338f to your computer and use it in GitHub Desktop.
Detecting where your library has been required from
# Some userland app code
$LOAD_PATH.unshift "."
require 'lib'
# Some other userland app code
$LOAD_PATH.unshift "."
require 'lib'
# Your library
require 'rbconfig'
def in_my_codebase?(f)
File.basename(f) == File.basename(__FILE__)
end
def in_local_ruby?(f)
f.index(RbConfig::TOPDIR) == 0
end
def detect_requiring_file
requiring_file = nil
begin
raise RuntimeError
rescue RuntimeError => e
files = e.backtrace.map { |line| line.split(":").first }
files.reject! { |f| in_my_codebase?(f) }
files.reject! { |f| in_local_ruby?(f) }
requiring_file = files.first
end
requiring_file
end
p "required_from #{detect_requiring_file}"
$ ruby app1.rb
required from app1.rb
$ ruby app2.rb
required from app2.rb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment