Is there a way to view the source code of a method from the Rails console?

Let's say I have the following class:

class User < ActiveRecord::Base
  def fullname
    "#{self.first_name} #{self.last_name}"
  end
end

Is it possible for me to go into the console and somehow look at the source code of the name-name method in the console? For example, it will look ...

irb(main):010:0> omg_console_you_are_awesome_show_source(User.fullname)
[Fri Jun 29 14:11:31 -0400 2012] => def fullname
[Fri Jun 29 14:11:31 -0400 2012] =>   "#{self.first_name} #{self.last_name}"
[Fri Jun 29 14:11:31 -0400 2012] => end

Or is there really any way to view the source code? Thank!

+10
source share
2 answers

You can also use pry (http://pry.github.com/ ), which is similar to IRB on steroids. You can do things like:

[1] pry(main)> show-source Array#each

From: array.c in Ruby Core (C Method):
Number of lines: 11
Owner: Array
Visibility: public

VALUE
rb_ary_each(VALUE ary)
{
    long i;

    RETURN_ENUMERATOR(ary, 0, 0);
    for (i=0; i<RARRAY_LEN(ary); i++) {
    rb_yield(RARRAY_PTR(ary)[i]);
    }
    return ary;
}
[2] pry(main)> show-doc Array#each

From: array.c in Ruby Core (C Method):
Number of lines: 11
Owner: Array
Visibility: public
Signature: each()

Calls block once for each element in self, passing that
element as a parameter.

If no block is given, an enumerator is returned instead.

   a = [ "a", "b", "c" ]
   a.each {|x| print x, " -- " }

produces:

   a -- b -- c --
+23
source

Not exactly what you're asking, but this Railscast can help.

It will teach you a trick that allows you to open a method in a text editor from the Rails console.

UPDATE:

, ... .

~/.irbrc

class Object
  def mate(method_name)
    file, line = method(method_name).source_location
    'mate '#{file}' -l #{line}'
  end
end

... mate - CLI TextMate (, subl Sublime Text).

helper.mate(:number_to_currency)

... number_to_currency - , .

, , Railscast Pro. , 9 . , , , , .

+3

All Articles