Created
May 20, 2025 09:53
-
-
Save skatkov/83648df077c94560af0e2eec95a855b1 to your computer and use it in GitHub Desktop.
Method detection code
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
# Raises an error when method is called, unless it was called by known caller. | |
# | |
# In your class: | |
# | |
# include MethodCallDetection | |
# detect_method_calls_of :method_to_detect do |trace| | |
# next true if trace[0].match?('path/of/direct_call.rb:123') | |
# next true if trace.any? { _1.match?('path/of/call_somewhere.rb') } | |
# end | |
module MethodCallDetection | |
extend ActiveSupport::Concern | |
class_methods do | |
def detect_method_calls_of(name) | |
# Make sure not to run on production here | |
define_method(name) do |*args| | |
trace = Kernel.caller | |
unless yield(trace) | |
Kernel.puts trace | |
Kernel.raise "Unknown call of #{self.class}##{name}" | |
end | |
super(*args) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment