1

I'm working on transforming legacy code to a new one in a new project. There are more than 100 of similar codes and I have to transform them to a slightly different new format. Basically, get a particular method from the legacy application, rename it, modify the content of the method to fit the new format, and put that method in a class for the new project. Since there are more than 100 of them, I want to do it programmatically, instead of manually copying and pasting and modifying.

Is there a way to get the source code of a method as a string dynamically? It must be only for a specific method, not the entire content of the class or file.

After that is done, I think I can just do gsub, or maybe use AST (Abstract Syntax Tree) to pass to Ruby2Ruby.

So I need more than the answers for the question How can I get source code of a methods dynamically and also which file is this method locate in?.

Any help will be greatly appreciated.

Community
  • 1
  • 1
tadatoshi
  • 118
  • 9

2 Answers2

1

After further investigation, I resorted to use live_ast gem to convert the method object to Abstract Syntax Tree and generate the code for the method from that Abstract Syntax Tree (it's using Ruby2Ruby underneath). Actually, live_ast provides a convenient method to_ruby to do the both steps.

It's working very well.

e.g.

require 'live_ast'
require 'live_ast/to_ruby'

SomeClassWithMethod.instance_method(:method_name).to_ruby
tadatoshi
  • 118
  • 9
0

You could use source_location to find the beginning of the method you're looking for, then parse the file from that point until the end of the method. You could examine each line of the file starting from the start of the method, incrementing a counter when you find the start of a block and decrementing it when you reach the end of a block, until the counter reaches 0.

Evan Kroske
  • 4,506
  • 12
  • 40
  • 59
  • Welcome to Stack Overflow! If my answer solves your problem, please accept it by clicking on the check mark beside the answer. That will reward me with reputation points. – Evan Kroske Jun 12 '11 at 01:46