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

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

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

 def bla puts "Hi There" end 

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

 puts get_definition(:bla) 

it will print

 "puts \"Hi There\"" 

Is there a canonical way to do this? I really did not need to do this before, and I know that this is not a common practice in rails.

I also do not want to define my method using meta-reflexive programming, and then store the string used to define my method. Any help is appreciated!

+6
source share
1 answer

I have no idea what John Highland writes about. There is no such method (in normal Ruby) as Method#source . The practical solution is to use pry gem . It has methods that allow you to access the source.

+1
source

Source: https://habr.com/ru/post/948027/


All Articles