Last updated January 18, 2011 04:57, by qmxme
Feedicon  

» JRuby Project Wiki Home Page
» Embedding JRuby Wiki Page

Embedding JRuby - Rewrite it!

Red Bridge

Features of Red Bridge

See Features of Red Bridge section.

Download

See Download section.

Getting Started

See Getting Started section.

Configurations

See Configurations section.

Code Examples

See RedBridgeExamples page.

Servlet Examples

See RedBridgeServletExamples page.

Rewriting from legacy ways

example 1

Suppose you want to rewrite Ruby code in your classpath, Mixed with java using Red Bridge, the code will be below:

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);
	}

}
class RubyRoot

  def start( root )
    puts root.toString
  end

end
Above produces:
{name=david}

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.

  • Mysql
  • Glassfish
  • Jruby
  • Rails
  • Nblogo
Terms of Use; Privacy Policy;
© 2010, Oracle Corporation and/or its affiliates
(revision 20120127.ac94057)
 
 
Close
loading
Please Confirm
Close