ruby2ruby is a gem created by the Seattle Ruby Brigade. You can install it, like any other gem, with gem install ruby2ruby. Once installed, it lets you peer inside a Class' methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$ irb irb(main):001:0> require 'rubygems' => true irb(main):002:0> require 'ruby2ruby' => true irb(main):003:0> class Foo irb(main):004:1> attr_accessor :fud irb(main):005:1> def initialize(fud) irb(main):006:2> @fud = fud irb(main):007:2> end irb(main):008:1> end => nil irb(main):009:0> Ruby2Ruby.translate Foo => "class Foo < Object\n attr_reader :fud\n \n attr_writer :fud\n \n def initialize(fud)\n @fud = fud\n end\nend" |
Here I've created a simple class. One thing that is interesting, the interpreter expands attr_accessor into both attr_reader and attr_writer for me automatically. One of the requirements of Ruby2Ruby is that it works on Classes, not on instances:
1 2 3 4 5 6 7 8 9 10 11 12 |
irb(main):010:0> f=Foo.new(5) => #<Foo:0x2b82e560d608 @fud=5> irb(main):011:0> Ruby2Ruby.translate f NoMethodError: undefined method `instance_methods' for #<Foo:0x2b82e560d608 @fud=5> from /usr/lib/ruby/gems/1.8/gems/ParseTree-2.1.1/lib/parse_tree.rb:115:in `parse_tree' from /usr/lib/ruby/gems/1.8/gems/ParseTree-2.1.1/lib/parse_tree.rb:99:in `parse_tree' from /usr/lib/ruby/gems/1.8/gems/ParseTree-2.1.1/lib/parse_tree.rb:71:in `translate' from /usr/lib/ruby/gems/1.8/gems/ruby2ruby-1.1.8/lib/ruby2ruby.rb:31:in `translate' from (irb):11 irb(main):012:0> Ruby2Ruby.translate f.class => "class Foo < Object\n attr_reader :fud\n \n attr_writer :fud\n \n def initialize(fud)\n @fud = fud\n end\nend" |
We can compare the code as it changes, too:
1 2 3 4 5 6 7 8 9 |
irb(main):013:0> class Foo irb(main):014:1> def something(bar) irb(main):015:2> puts bar irb(main):016:2> end irb(main):017:1> end => nil irb(main):018:0> Ruby2Ruby.translate Foo => "class Foo < Object\n attr_reader :fud\n \n attr_writer :fud\n \n def initialize(fud)\n @fud = fud\n end\n \n def something(bar)\n puts(bar)\n end\nend" |
There's a lot more which can be done here, and it will be the subject of a further entry.
