views:

122

answers:

2

I'm embedding JRuby in Java, because I need to call some Ruby methods with Java strings as arguments. The thing is, I'm calling the methods like this:


String text = ""; // this can span over multiple lines, and will contain ruby code
Ruby ruby = Ruby.newInstance();
RubyRuntimeAdapter adapter = JavaEmbedUtils.newRuntimeAdapter();
String rubyCode = "require \"myscript\"\n" +
                            "str = build_string(%q~"+text+"~)\n"+
                            "str";
IRubyObject object = adapter.eval(ruby, codeFormat);

The thing is, I don't know what strings I can use as delimiters, because if the ruby code I'm sending to build_string will contain ruby code. Right know I'm using ~,but I think this could break my code. What characters can I use as delimiters to make sure my code will work no matter what the ruby code is?

A: 

Since string text contain contain any character, there is no character left to use for quotation escaping like the ~ you're using now. You would still need to escape the tilde in string text in java and append that one to the string you're building.

Something like (untested, not a Java guru):

String rubyCode = "require \"myscript\"\n" +
                            "str = build_string(%q~" + text.replaceAll("~", "\\~") + "~)\n"+
                            "str";
Rutger Nijlunsing
+1  A: 

use the heredoc format:

"require \"myscript\"\n" +
          "str = build_string(<<'THISSHOUDLNTBE'\n" + text + "\nTHISSHOULDNTBE\n)\n"+
          "str";

this however assumes you won't have "THISSHOULDNTBE" on a separate line in the input.

SztupY
I'll generate a string with the heredoc begin and end.
Geo