2

Is there a way to find out from where a method was included in Ruby / Ruby on Rails?

For example, from searching the Rails API I know that:

  • link_to comes from ActionView::Helpers::UrlHelper, and
  • pluralize come from ActionView::Helpers::TextHelper

But is there a way to find out in Ruby itself? i.e. inirb, or the Rails console?

mjeppesen
  • 1,040
  • 1
  • 10
  • 14
  • 1
    You might want to read this also: http://stackoverflow.com/questions/3393096/how-can-i-get-source-code-of-a-methods-dynamically-and-also-which-file-is-this-m – Casper Apr 25 '12 at 22:50
  • 1
    And this: http://stackoverflow.com/questions/175655/how-to-find-where-a-method-is-defined-at-runtime – Casper Apr 25 '12 at 22:51

2 Answers2

3

Yes:

@object.method(:method_name)

For example:

@object.method(:pluralize)
Casper
  • 33,403
  • 4
  • 84
  • 79
x1a4
  • 19,417
  • 5
  • 40
  • 40
  • `@s = "error"; @s.pluralize(:method_name)` doesn't give `ActionView::Helpers::TextHelper`, though. Have I misunderstood? – mjeppesen Apr 25 '12 at 22:31
  • @MatthewJeppesen Try `@s.method(:pluralize)` :) – Casper Apr 25 '12 at 22:36
  • `@s.method(:pluralize)` `# => #` ... – mjeppesen Apr 25 '12 at 22:38
  • @MatthewJeppesen That's the correct result. `pluralize` is a method added to `String` directly. You can see its definition [here](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/string/inflections.rb#L25) – x1a4 Apr 26 '12 at 04:26
1

Whatever context you're in you can get the source location by using:

obj.method(:method).source_location

It won't give you exactly what you want, but the Rails core developers are good about properly namespacing things. The following example can be run from the rails console:

Time.method(:zone).source_location

["/Users/pete/.rvm/gems/ruby-1.9.2-p290@gemset/gems/activesupport-3.2.3/lib/active_support/core_ext/time/zones.rb", 9]

Then you can go to the Rails source and search for that file. Hint: type 't' on Github and start typing. It will bring you to that file and you can see that it is defined directly on the Time class.

Peter Brown
  • 50,956
  • 18
  • 113
  • 146