Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to view a method's source code 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 view the fullname method's source code output in the console somehow? Like, it would look like...

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 really any way to view source code? Thanks!

like image 495
Orlando Avatar asked Jun 29 '12 18:06

Orlando


2 Answers

You can also use pry (http://pry.github.com/) which is like IRB on steroids. You can do stuff 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 --
like image 147
Ylan S Avatar answered Nov 16 '22 04:11

Ylan S


Not exactly what you are asking, but this Railscast might help.

It teaches you a trick that will allow you to open the method in your text editor from the Rails console.

UPDATE:

I just realized that link is behind a paywall... Here's a summary of the trick.

Add this to your ~/.irbrc file

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

...where mate is the CLI command to open TextMate (of course subl could be used here for Sublime Text).

Then in the console simply call

helper.mate(:number_to_currency)

...where number_to_currency is the method who's source you want to view.

BTW, if you don't already, you should subscribe to Railscast Pro. IMO, there is not a better way to spend 9 dollars per month. And to disclose, I have no relationship with that site other then being a satisfied customer.

like image 31
Bob. Avatar answered Nov 16 '22 04:11

Bob.