kwikness
kwikness

Reputation: 1445

How To Determine What Class/Module a Method is in

Coming from working with Java in Eclipse, it's always been extremely easy for me to determine where a method was defined: simply ctrl+click the method call and it brings you to the method definition in its containing class. Obviously it's Eclipse that makes a lot of this happen, but even with plain old Java, we still have the import statements to fall back on.

Method lookups seem to be very difficult with Rails development.

Here's an example:

require 'test_helper'

class UserStoriesTest < ActionDispatch::IntegrationTest
  fixtures: products

  LineItem.delete_all
  Order.delete_all
  ruby_book = products(:ruby)

  get "/"
  assert_response :success
  assert_template "index"

  cart = Cart.find(session[:cart_id])
  assert_equal 1, cart.line_items.size
  assert_equal ruby_book, cart.line_items[0].product

  get "/orders/new"
  assert_response :success
  assert_template "new"
end

Let's say I wanted to take a closer look at the assert_equal method. If I was working with Java and the class that contained assert_equal would probably be described by an import statement in this class with its location explicitly specified (e.g. java.lang.SomeCoreClass). Since I have no idea where the hell this method is defined, what I end up doing is Googling for "assert_equal" to find that the method I'm investigating is (probably and hopefully) defined in Test::Unit::Assertions.

I'm interested to hear from a few people on their approaches to determining method locations.

Upvotes: 0

Views: 79

Answers (2)

ChuckE
ChuckE

Reputation: 5688

try this:

class Bong
  def smoke
    puts "smoke"
  end
end

Bong.method(:smoke)
Bong.method(:smoke).source_location

Upvotes: 4

Raghu
Raghu

Reputation: 2563

You can use method(:<method_name>).owner to track the class of the method. In your case it would be method(:assert_equal).owner.

method#owner

Upvotes: 1

Related Questions