This post originated from an RSS feed registered with Ruby Buzz
by Ryan Davis.
Original Post: RubyToRuby
Feed Title: Polishing Ruby
Feed URL: http://blog.zenspider.com/index.rdf
Feed Description: Musings on Ruby and the Ruby Community...
So... drbrain comes up to me in an IM and says flgr is saying it'd be really cool if you could ask a method for its source. I know what he is doing, baiting me like that, but I play along anyways to see what the outcome is like. drbrain and I talked about it and thought it'd be really cool if our ruby2c system added a to_c method to the Method class. That isn't hard at all really, so we added:
class Method
# with_class_and_method_name is a silly method.
# Implementation is an exercise for the reader.
def to_sexp
with_class_and_method_name do |klass, method|
ParseTree.new.parse_tree_for_method(klass, method)
end
end
def to_c
with_class_and_method_name do |klass, method|
RubyToC.translate(klass, method)
end
end
end
But the question came up... can we do this to display ruby code? The answer is yes, and it only took me about 30 minutes to get the proof of concept up and running. First, the example code:
class Example
def example(arg1)
return "Blah: " + arg1.to_s
end
end
e = Example.new
puts "sexp:"
p e.method(:example).to_sexp
puts "C:"
puts e.method(:example).to_c
puts "Ruby:"
puts e.method(:example).to_ruby
Cool huh? I can now translate any method to C or get the ruby code for it (sans-comments unfortunately) simply by calling to_c or to_ruby on the method itself!