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!
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.
In short: no, Ruby does not support nested methods.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With