Created
February 6, 2015 15:05
-
-
Save lazyatom/547a1cca0f3d90b1338f to your computer and use it in GitHub Desktop.
Detecting where your library has been required from
This file contains hidden or 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
# Some userland app code | |
$LOAD_PATH.unshift "." | |
require 'lib' |
This file contains hidden or 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
# Some other userland app code | |
$LOAD_PATH.unshift "." | |
require 'lib' |
This file contains hidden or 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
# 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}" |
This file contains hidden or 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
$ 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