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?

2

2 Answers 2

3

Yes:

@object.method(:method_name)

For example:

@object.method(:pluralize)
Sign up to request clarification or add additional context in comments.

4 Comments

@s = "error"; @s.pluralize(:method_name) doesn't give ActionView::Helpers::TextHelper, though. Have I misunderstood?
@MatthewJeppesen Try @s.method(:pluralize) :)
@s.method(:pluralize) # => #<Method: String#pluralize> ...
@MatthewJeppesen That's the correct result. pluralize is a method added to String directly. You can see its definition here
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.