Last Updated: February 25, 2016
·
1.379K
· JoeyButler

Track down source code with Kernel#method

# TL;DR
puts method_find = [].method(:find)
# => #<Method: Array(Enumerable)#find>

if RUBY_VERSION =~ /^1.8/
  [method_find.__line__, method_find.__line__]
else
  method_find.source_location
end

# On to our featured presentation. :)
#
# Ruby's dynamic nature gives you a myraid of ways to
# construct your objects.
# Sometimes this can bite you and put you in a situation 
# where it's tricky to track down where a method
# is defined.
#
# We can easily solve this with Kernel#method.

module Bar
  def say
    'hello'
  end
end

class Foo
  include Bar
end

method_say = Foo.new.method(:say)
puts method_say # => #<Method: Foo(Bar)#say>

# What is really nifty is that we can ask the method object 
# which file it was defined in as well as on which line.

if RUBY_VERSION =~ /^1.8/
  puts method_say.__file__
  puts method_say.__line__
else
  puts method_say.source_location
end

# This is also very useful when deciphering if the method
# is defined in the ruby core classes or in 
# a library/framework.

# class Cat <ActiveRecord::Base
# end
# puts Cat.method(:find)
# => #<Method: Cat(Table doesn't exist)(ActiveRecord::Base).find>

puts [].method(:find)
# => #<Method: Array(Enumerable)#find>

1 Response
Add your response