0

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?

starblue
  • 55,348
  • 14
  • 97
  • 151
Geo
  • 93,257
  • 117
  • 344
  • 520

2 Answers2

1

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
  • 10,291
  • 8
  • 64
  • 87
0

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
  • 4,861
  • 1
  • 21
  • 24