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\""
0

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
How does this work in cases where the source file doesn't exist at runtime? E.g. AOT-compiled binaries?
Jörg: it doesn't. See caveats in readme. method_source has similar limitations.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.