linjunhalida linjunhalida - 5 months ago 18
Ruby Question

how to get source code text in ruby?

inspired by some lisp magic of runtime edit sourcecode,

I want to do it in ruby. looks like I cannot get sourcecode from method/class,
is there a way to do it?

I write a sample sourcecode here:

def helloworld n
"hello #{n}"
end

o = Kernel.method :helloword

Kernel.define_singleton_method o.name do |n|
eval o.source_code.sub('hello', 'hello world')
end

helloworld 'halida' #=> 'hello world halida'

Answer

You can't get the string representation of a part of the code, edit it and expect Ruby to reevaluate your changes. The only way to do something near to what you want is using ParseTree to get s-expressions of the source, edit and use Ruby2Ruby to generate a string of ruby code. Them add def ... and end to the string and call eval with it.

It's too hard and error-prone to be useful in a real-world situation. But I don't know any other way.

Note: ParseTree only works on Ruby 1.8.

Comments