孙悟空
孙悟空

Reputation: 1285

How to find out where a function is overridden?

In my Rails project, I saw the link_to is overridden in config/initializers/extend_action_view.rb

module ActionView
  module Helpers
    def link_to(name, options = {}, html_options = nil)
    ...
    end
  end
end

I found that with the famous command line in linux grep -r 'def link_to' *.

My question is : Is there a way to find out it in rails console ? Is there a native function rails or ruby can give us the path of file ? Something like .ancestors for a object.

ps: My IDE is vi

Upvotes: 3

Views: 976

Answers (2)

akuhn
akuhn

Reputation: 27823

Use $ command in pry gem

Insert binding.pry in your code, which sets a breakpoint and then in the Pry commandline use the $ command

[1] pry(#<AdminController>)> $ Person.find

From: /Users/joe_example/.rvm/gems/ruby-1.9.3-p551/gems/composite_primary_keys-8.1.0/lib/composite_primary_keys/core.rb @ line 21:
Owner: ActiveRecord::Core::ClassMethods
Visibility: public
Number of lines: 38

def find(*ids) # :nodoc:
  # We don't have cache keys for this stuff yet
  return super unless ids.length == 1
  ...

The $ command is literally worth dollars. It shows you where a method is defined as well as the source code.

Upvotes: 1

Ilya
Ilya

Reputation: 13487

If you use the pry gem, you can find it by using Method#source_location. Pass binding.pry in your view and render it. Then write:

method(:link_to).source_location
=> ["path_to_helper.rb", 124]

Upvotes: 2

Related Questions