-1

If the source of the any method is written explicitly in a file, there is a neat method to display the code:

A.instance_method(:foo).source

but if i define class and methods in it dynamically with

Object.const_set(dynamic_name, Class.new { def foo() puts 'bar' end })

i receive an error when try to get the source of this method, when use instance_method(:foo).source in this case

MethodSource::SourceNotFoundError: Could not load source for : No such file or directory @ rb_sysopen - (eval)

How can i get the source of dynamically defined method? Is it possible at all?

okliv
  • 3,909
  • 30
  • 47
  • According to the gem's documentation, there are [limitations](https://github.com/banister/method_source#limitations): it _"Cannot return source for C methods"_ and it _"Cannot return source for dynamically defined methods"_. So no, it's not possible with that gem. – Stefan Oct 05 '17 at 08:22
  • @Stefan, i saw this, but there is no constraints to use only that gem – okliv Oct 05 '17 at 08:25
  • When using a library, write that. – sawa Oct 05 '17 at 08:38
  • done, my majesty – okliv Oct 05 '17 at 08:44

1 Answers1

3

At the very least, you can get bytecode (assuming you use MRI)

puts RubyVM::InstructionSequence.disasm(A.instance_method(:foo))
# >> == disasm: #<ISeq:foo@->================================================
# >> 0000 trace            8                                               (   3)
# >> 0002 trace            1
# >> 0004 putself          
# >> 0005 putstring        "bar"
# >> 0007 opt_send_without_block <callinfo!mid:puts, argc:1, FCALL|ARGS_SIMPLE>, <callcache>
# >> 0010 trace            16
# >> 0012 leave            
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367