6

Let's say I have a function called bla defined somewhere in my rails app.

Is there a way in ruby or rails through which I can print the code dynamically/programmatically used to define that function ? So for example:

def bla
   puts "Hi There"
end

and then if I call a function like, for example, get_definition:

puts get_definition(:bla)

this would print out

"puts \"Hi There\""

Is there a canonical way of doing this ? I haven't actually needed to do this before, and I know this is not really common practice in rails.

I also don't want to define my method using meta (reflective) programming and then store the string used to define my method. Any help is appreciated!

Cosmin Atanasiu
  • 2,532
  • 3
  • 21
  • 26
  • http://stackoverflow.com/a/11544229/1004274 – oldergod Jun 25 '13 at 00:31
  • Duplicate of http://stackoverflow.com/questions/3220623/meta-programming-output-method-body-as-text – Peter Alfvin Jun 25 '13 at 00:33
  • Good points, seems it's a duplicate of both questions (weird, since those questions are duplicates of each other then)... none of those actually answer my question and none of them can be found on google when searching 'programatically' or I would've found both. But a duplicate is a duplicate – Cosmin Atanasiu Jun 25 '13 at 00:43
  • Good question. Super interested too see the answer – OneChillDude Jun 25 '13 at 03:04
  • possible duplicate of [How can I get source code of a methods dynamically and also which file is this method locate in](http://stackoverflow.com/questions/3393096/how-can-i-get-source-code-of-a-methods-dynamically-and-also-which-file-is-this-m) – the Tin Man Jun 25 '13 at 04:35
  • Not really a duplicate if the answer in here is for 1.9.3 which was released after that question was posted – Cosmin Atanasiu Jun 26 '13 at 17:10

1 Answers1

1

I have no idea what John Hyland is writing about. There is no such method (in plain Ruby) as Method#source. The practical solution is to use the pry gem. It has methods to let you access the source.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    Not sure who down voted you, but I will try to use the pry gem as well. @John-Hyland actually has a good point, the .source_location method does work on 1.9.2. I have yet to test the .source method in 1.9.3 – Cosmin Atanasiu Jun 25 '13 at 03:16
  • @CosminAtanasiu Yes, `Method#source_location` is there for a long while. As I wrote, there is no such method as `Method#source`. I have used 1.9.2 as well as 1.9.3, and there were no such method. Now, I use 2.0, and there is no such method. – sawa Jun 25 '13 at 03:18
  • I will review it in the next few days to see – Cosmin Atanasiu Jun 25 '13 at 03:26
  • 3
    Oh man, you are totally right. I was actually testing this in pry, which adds the `.source` method to the Method class. Doh! I will delete my answer, sorry for the misinformation. – John Hyland Jul 02 '13 at 16:16