What is the most reliable way to generate and/or parse and modify a Ruby source file from within ruby?
That is, I want to e.g. create a new ruby source file or change a few lines of code in a class in a source file to e.g. add or remove methods or calls or whatever.
Is there a library for this perhaps?
Ruby2Ruby is one such gem. There may be others. From the readme file:
require 'rubygems'
require 'ruby2ruby'
require 'ruby_parser'
require 'pp'
ruby = "def a\n puts 'A'\nend\n\ndef b\n a\nend"
parser = RubyParser.new
ruby2ruby = Ruby2Ruby.new
sexp = parser.process(ruby)
pp sexp
p ruby2ruby.process(sexp)
## outputs:
s(:block,
s(:defn,
:a,
s(:args),
s(:scope, s(:block, s(:call, nil, :puts, s(:arglist, s(:str, "A")))))),
s(:defn, :b, s(:args), s(:scope, s(:block, s(:call, nil, :a, s(:arglist))))))
"def a\n puts(\"A\")\nend\ndef b\n a\nend\n"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With