Created
November 18, 2009 20:05
-
-
Save jaydonnell/238194 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package play; | |
import org.jruby.embed.PathType; | |
import org.jruby.embed.ScriptingContainer; | |
public class ClassUseSample { | |
public ScriptingContainer container; | |
public String file; | |
public ClassUseSample(String filename) { | |
file = filename; | |
System.out.println("[" + getClass().getName() + "]"); | |
container = new ScriptingContainer(); | |
container.runScriptlet(PathType.CLASSPATH, file); | |
} | |
public RubyObject rubyClass(String classname) { | |
Object obj = container.runScriptlet(classname); | |
return new RubyObject(obj); | |
} | |
public RubyObject newRubyObject(String classname, Object[] args) { | |
RubyObject rc = rubyClass(classname); | |
Object robj = rc.send("new", args, Object.class); | |
return new RubyObject(robj); | |
} | |
public class RubyObject { | |
private Object obj; | |
public RubyObject(Object object) { | |
obj = object; | |
} | |
public <T> T send(String methodName, Class<T> returnType) { | |
return container.callMethod(obj, methodName, returnType); | |
} | |
public <T> T send(String methodName, Object singleArg, Class<T> returnType) { | |
return container.callMethod(obj, methodName, singleArg, returnType); | |
} | |
public <T> T send(String methodName, Object[] args, Class<T> returnType) { | |
return container.callMethod(obj, methodName, args, returnType); | |
} | |
} | |
public static void main(String[] args) { | |
ClassUseSample ruby = new ClassUseSample("tree.rb"); | |
Object[] call_args = {"pink", "March-April"}; | |
RubyObject flower = ruby.newRubyObject("Flower", call_args); | |
System.out.println(flower.send("color", String.class)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Tree | |
attr_reader :name, :shape, :flower | |
def initialize(name, shape, flower) | |
@name, @shape, @flower = name, shape, flower | |
end | |
def to_s | |
"#{name.capitalize} is a #{shape} shaped tree, and blooms #{flower.color} flowers in #{flower.bloomtime}." | |
end | |
def update(color, bloomtime) | |
flower.color = color | |
flower.bloomtime = bloomtime | |
end | |
end | |
class Flower | |
attr_accessor :color, :bloomtime | |
def initialize(color, bloomtime) | |
@color, @bloomtime = color, bloomtime | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment