Convert Ruby code to string

I refactored a code that I did not write, and found a line that looks like this (this is a lot more, I used a bit for this example):

system("rubyw -e \"require 'win32ole'; @autoit=WIN32OLE.new('AutoItX3.Control');") 

To improve readability, I reorganized it into

 do_something = "rubyw -e \" require 'win32ole' @autoit=WIN32OLE.new('AutoItX3.Control')" system do_something 

Then I wanted to make some changes, but since the code I'm working on is on the line, I lose syntax highlighting, matching in brackets and all that is good.

Is there an easy way to write some code outside the string and then convert it to a string?

I searched the web and stackoverflow but couldn't find the answer.

For more information, check out the source code at bret / watir (Watir :: FileField # set, line 445) and my plug in zeljkofilipin / watir (lines 447-459).

+4
source share
3 answers

You can use the following syntax:

 do_something = <<SOMETHING rubyw -e require 'win32ole' @autoit=WIN32OLE.new('AutoItX3.Control') SOMETHING 

Apparently this is a heredoc ! You can find another example here (doc) .

This does not mean that the team will not worry about the presence of line breaks. However, you could run its system do_something.split(/\r\n/).join('') or something like that.

+6
source

Well, you can just put the code in an external file and load it.

Alternatively, if I remember correctly, Ruby files may contain DATA sections:

 # Sample ruby file: puts DATA.readline() __END__ foo bar 

This should print " foo bar ". You can put your code in a data segment. In any case, your editor will still highlight the syntax for the DATA segment.

+5
source

Ruby2ruby sounds like what you are asking.

http://seattlerb.rubyforge.org/ruby2ruby/

+1
source

All Articles