views:

409

answers:

3

I am refactoring some code that I did not write, and I found a line that looks like this (it is much longer, i used just a little bit for this example):

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

To increase readability, I refactored it to

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 am working on is in a string, I loose syntax highlighting, parenthesis matching and all that good stuff.

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

I have searched the web and stackoverflow, but could not find the answer.

For more information, take a look at original code at bret/watir (Watir::FileField#set, line 445), and my fork at zeljkofilipin/watir (lines 447-459).

+2  A: 

Well, you could just put the code into an external file and load that.

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 could put your code in the data segment. With any luck, your editor will still provide syntax highlighting for the DATA segment.

Konrad Rudolph
Is it just me, or is something wrong with your example? > puts DATA NameError: uninitialized constant DATA from (irb):1
Željko Filipin
It works for me … no error there. I've updated the source code though, to create the right output.
Konrad Rudolph
Thanks, looks like the first time readline was missing.
Željko Filipin
+3  A: 

You can use the following syntax:

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

Apparently it's a heredoc! You can find another example here(doc).

That's not to say that the command won't freak out about having line breaks in there. However you could likely run it by system do_something.split(/\r\n/).join('') or something like that.

wombleton
It's called a "here document", or "heredoc" (http://en.wikipedia.org/wiki/Here_document)
Dave Ray
vim highlights heredocs as strings. Also, if you want a multiline string without escaping quotes, %{} is a more rubyish way to do it
Mk12
+1  A: 

Ruby2ruby sounds kind of like what you're asking.

seattlerb.rubyforge.org/ruby2ruby/