Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to view (or print) a method definition programatically in rails?

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!

like image 388
Cosmin Atanasiu Avatar asked Jun 25 '13 00:06

Cosmin Atanasiu


People also ask

How to define method dynamically in Ruby?

define_method is a method defined in Module class which you can use to create methods dynamically. To use define_method , you call it with the name of the new method and a block where the parameters of the block become the parameters of the new method.

Can you call a method inside a method Ruby?

In short: no, Ruby does not support nested methods.

Where method is defined Ruby?

In Ruby the method for object can be defined from many places: modules, inheritance, meta-programming, other language's extensions and etc. Imagine that you have installed a lot of gems in your application and every gem potentially can define or redefine method on any object.


1 Answers

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.

like image 110
sawa Avatar answered Oct 27 '22 14:10

sawa