Skip to content

Instantly share code, notes, and snippets.

@jimweirich
Last active June 9, 2021 05:27
Show Gist options
  • Save jimweirich/4950443 to your computer and use it in GitHub Desktop.
Save jimweirich/4950443 to your computer and use it in GitHub Desktop.
# My take on Mike's source_for method.
# (see http://pragmaticstudio.com/blog/2013/2/13/view-source-ruby-methods)
#
# (1) I named it 'src' rather than source_for (ok, I'm a lazy typer).
# (2) The edit function was broken out as a separate function.
# (3) The edit function is for emacs
# (4) If the method is not defined on the object, and the object
# is a class, then see if it is an instance method on the class.
#
# The fourth point allows my to say:
#
# src(Person, :update)
# or src(Person.new, :update)
#
def edit(file, line)
`emacsclient -n +#{line} #{file}`
end
def src(object, method)
if object.respond_to?(method)
meth = object.method(method)
elsif object.is_a?(Class)
meth = object.instance_method(method)
end
location = meth.source_location
edit(*location) if location
location
rescue NameError => ex
nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment