Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate/modify Ruby source files from within Ruby

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?

like image 635
mydoghasworms Avatar asked Apr 26 '26 21:04

mydoghasworms


1 Answers

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"
like image 159
Andrew Grimm Avatar answered Apr 29 '26 10:04

Andrew Grimm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!