Last active
August 29, 2015 14:04
-
-
Save dexterous/d5e0021021dd39397ffa to your computer and use it in GitHub Desktop.
A quick usage sample of the JSR-223 Script interface API
This file contains 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
apply plugin: 'application' | |
mainClassName = 'foo.RubyFoo' | |
dependencies { | |
runtime files('~/.rvm/rubies/jruby-1.7.12/lib/jruby.jar') | |
} |
This file contains 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
DEFAULT_GREETING = 'Hello' | |
class Greeter | |
def greet name='World' | |
"#{@greeting}, #{name}!" | |
end | |
private | |
def initialize greeting=DEFAULT_GREETING | |
@greeting = greeting | |
end | |
end | |
DEFAULT_GREETER = Greeter.new | |
def default_greeting | |
DEFAULT_GREETER.greet | |
end |
This file contains 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 foo; | |
public interface Greeter { | |
String greet(); | |
String greet(String name); | |
String defaultGreeting(); | |
} |
This file contains 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 foo; | |
import java.io.*; | |
import javax.script.*; | |
public class RubyFoo { | |
public static void main(String[] arg) { | |
ScriptEngineManager manager = new ScriptEngineManager(); | |
ScriptEngine engine = manager.getEngineByExtension("rb"); | |
try { | |
engine.eval(script("/foo.rb")); | |
Invocable invoker = (Invocable)engine; | |
System.out.println(invoker.invokeFunction("default_greeting")); | |
System.out.println(invoker.invokeMethod(engine.eval("DEFAULT_GREETER"), "greet", "Me")); | |
Greeter greeter = invoker.getInterface(Greeter.class); | |
System.out.println(greeter.defaultGreeting()); | |
Greeter indian = invoker.getInterface(engine.eval("Greeter.new 'Namaste'"), Greeter.class); | |
System.out.println(indian.greet()); | |
System.out.println(indian.greet("Bandhu")); | |
} catch (ScriptException x) { | |
System.out.println("Could not execute script.\n" + x); | |
} catch (NoSuchMethodException x) { | |
System.out.println("Could not find function/method"); | |
} | |
} | |
private static Reader script(String path) { | |
return new InputStreamReader(RubyFoo.class.getResourceAsStream(path)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment