Skip to content

Instantly share code, notes, and snippets.

@ivorpad
Created February 2, 2024 12:23
Show Gist options
  • Save ivorpad/2abe86b313a543ccb80f4fe773ae010f to your computer and use it in GitHub Desktop.
Save ivorpad/2abe86b313a543ccb80f4fe773ae010f to your computer and use it in GitHub Desktop.
# config/initializers/method_source_locator.rb
# Utility to find the source location of a method based on its receiver and name
def source_location(receiver, method_name)
method_object = if receiver.singleton_class.method_defined?(method_name) || receiver.singleton_class.private_method_defined?(method_name)
# Class method
receiver.method(method_name)
elsif receiver.method_defined?(method_name) || receiver.private_method_defined?(method_name)
# Instance method
receiver.instance_method(method_name)
else
raise NoMethodError, "Undefined method `#{method_name}` for #{receiver}"
end
method_object.source_location
rescue NameError => e
raise NameError, "Error finding method: #{e.message}"
end
# For a class method
source_location(User, :hello)
# For an instance method
source_location(User.new, :instance_method_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment