Last updated January 18, 2011 04:57, by qmxme
[[Home|» JRuby Project Wiki Home Page]]<br/>
[[RedBridge|» Embedding JRuby Wiki Page]]
<h1>Embedding JRuby - Rewrite it!</h1>
__TOC__
= Red Bridge =
== Features of Red Bridge ==
See [[RedBridge#Features_of_Red_Bridge|Features of Red Bridge]] section.
== Download ==
See [[RedBridge#Download|Download]] section.
== Getting Started ==
See [[RedBridge#Getting_Started|Getting Started]] section.
== Configurations ==
See [[RedBridge#Configurations|Configurations]] section.
== Code Examples ==
See [[RedBridgeExamples]] page.
== Servlet Examples ==
See [[RedBridgeServletExamples]] page.
== Rewriting from legacy ways ==
=== example 1 ===
Suppose you want to rewrite [[DirectJRubyEmbedding#Ruby_code_in_your_classpath,_Mixed_with_java|Ruby code in your classpath, Mixed with java]] using Red Bridge, the code will be below:
<pre name="java">
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jruby.embed.ScriptingContainer;
public class RubyLauncher {
private ScriptingContainer container;
private Object receiver;
private RubyLauncher(String initialRequire, String rootRubyClass, String rootMethod) {
String bootstrap =
"require \"" + initialRequire + "\"\n"+
"class Bootstrap \n" +
" def execute root_object \n" +
" " + rootRubyClass + ".new." + rootMethod + "(root_object) \n" +
" end \n" +
"end \n" +
"Bootstrap.new";
container = new ScriptingContainer();
String currentDir = container.getCurrentDirectory();
String[] paths = {currentDir + "/bin"};
List<String> loadPaths = Arrays.asList(paths);
//container.getProvider().setLoadPaths(loadPaths); // JRuby 1.4
container.setLoadPaths(loadPaths); // JRuby 1.5
receiver = container.runScriptlet(bootstrap);
}
private void call(Object obj) {
container.callMethod(receiver, "execute", obj, null);
}
public static void main(String[] args) {
Map<String, Object> root = new HashMap<String, Object>();
root.put("name", "david");
RubyLauncher launcher = new RubyLauncher("ruby/ruby_root.rb", "RubyRoot", "start");
launcher.call(root);
}
}</pre>
<pre name="ruby">
class RubyRoot
def start( root )
puts root.toString
end
end</pre>
Above produces:
<pre>
{name=david}
</pre>
I used Eclipse Java project to run the code, so I had a path, "bin," in a load path. Please change the path to fit it in yours. Also, change the first argument of RubyLauncher constructor so that ruby_root.rb can be found from the load path. I had ruby_root.rb file under bin/ruby directory when I ran the code.





