Ruby:如何动态获取方法内容并将其写入文件?
我正在努力将旧代码转换为新项目中的新代码。 有超过 100 个类似的代码,我必须将它们转换为稍微不同的新格式。 基本上,从遗留应用程序中获取特定方法,对其进行重命名,修改该方法的内容以适应新格式,然后将该方法放入新项目的类中。 由于有100多个,我想以编程方式完成,而不是手动复制粘贴和修改。
有没有办法动态获取方法的源代码作为字符串? 它必须仅适用于特定方法,而不是类或文件的全部内容。
完成之后,我想我可以只做 gsub,或者使用 AST(抽象语法树)传递给 Ruby2Ruby。
所以我需要的不仅仅是问题的答案 如何动态获取方法的源代码以及该方法位于哪个文件中?。
任何帮助将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过进一步调查,我求助于使用 live_ast gem 将方法对象转换为抽象语法树并生成代码抽象语法树中的方法(它在下面使用 Ruby2Ruby)。
实际上,live_ast 提供了一个方便的方法 to_ruby 来完成这两个步骤。
它运行得很好。
例如
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.
您可以使用
source_location
查找您要查找的方法的开头,然后从该点解析文件直到方法结尾。您可以从方法的开头开始检查文件的每一行,当找到块的开头时递增计数器,并在到达块的末尾时递减计数器,直到计数器达到 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.