0

Is there anyway to programmatically return the contents of a ruby method as a string? For example something like this?

class Foo
  def foo_method
    some_code = "goes here"
  end
end

puts Foo.method_body(:foo_method) # => "some_code = \"goes here\""
Jake Hoffner
  • 1,037
  • 9
  • 17

1 Answers1

1

Yes, sort of. :-)

I had to implement a similar feature (grab the source of a block) as part of Wrong and you can see how (and maybe even reuse the code) in chunk.rb (which relies on Ryan Davis' RubyParser as well as some pretty funny source file glomming code). You'd have to modify it to use Method#source_location and maybe tweak some other things so it does or doesn't include the def.

BTW I think Rubinius has this feature built in. For some reason it's been left out of MRI (the standard Ruby implementation), hence the hack.

Update: this answer points us to the method_source gem which seems to be a (relatively) clean, one-shot solution, using a similar algorithm (keep glomming lines from a source file until you stop getting parse errors).

Community
  • 1
  • 1
AlexChaffee
  • 8,092
  • 2
  • 49
  • 55
  • Thanks this is really helpful. As a bonus - Wrong might be come in handy for what I am working on, not just for the chunk file. – Jake Hoffner Feb 06 '13 at 22:12
  • I hope so! I've been using Wrong as a dumping ground for all my useful testing helpers; I'd love it if others get some use out of it too. – AlexChaffee Feb 06 '13 at 22:27
  • How does this work in cases where the source file doesn't exist at runtime? E.g. AOT-compiled binaries? – Jörg W Mittag Feb 06 '13 at 23:19
  • Jörg: it doesn't. See [caveats](https://github.com/sconover/wrong#algorithm) in readme. `method_source` has similar limitations. – AlexChaffee Feb 07 '13 at 15:15