public class ScriptingContainer extends Object implements EmbedRubyInstanceConfigAdapter
PropertyName and AttributeName
for more details. Be aware that the per-container properties should be set prior to
get Ruby runtime being instantiated; otherwise, default values are applied to.
ScriptingContainer delays Ruby runtime initialization as much as possible to
improve startup time. When values are put into the ScriptingContainer, or runScriptlet
method gets run the runtime is created internally. However, the default, singleton
local context scope behave slightly different. If a Ruby runtime has been already
instantiated by another ScriptingContainer, application, etc, the same runtime
will be re-used.
Below are examples.
The first Example is a very simple Hello World. After initializing a ScriptingContainer,
a Ruby script, puts "Hello World!", runs and produces "Hello World!."
Example 1:
ScriptingContainer container = new ScriptingContainer();
container.runScriptlet("puts \"Hello World!\"");
Produces:
Hello World!
The second example shows how to share variables between Java and Ruby.
In this example, a local variable "x" is shared. To make this happen,
a local variable behavior should be transient or persistent.
As for JSR223 JRuby engine, set these types using a System property,
org.jruby.embed.localvariable.behavior.
If the local variable behavior is one of transient or persistent,
Ruby's local, instance, global variables and constants are available to share
between Java and Ruby. (A class variable sharing does not work on current version)
Thus, "x" in Java is also "x" in Ruby.
Example 2:
ScriptingContainer container = new ScriptingContainer();
container.put("x", 12345);
container.runScriptlet("puts x.to_s(2)");
Produces:
11000000111001
The third examples shows how to keep local variables across multiple evaluations.
This feature simulates BSF engine for JRuby. In terms of Ruby semantics,
local variables should not survive after the evaluation has completed. Thus,
this behavior is optional, and users need to specify LocalVariableBehavior.PERSISTENT
when the container is instantiated.
Example 3:
ScriptingContainer container = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
container.runScriptlet("p=9.0");
container.runScriptlet("q = Math.sqrt p");
container.runScriptlet("puts \"square root of #{p} is #{q}\"");
System.out.println("Ruby used values: p = " + container.get("p") + ", q = " + container.get("q"));
Produces:
square root of 9.0 is 3.0
Ruby used values: p = 9.0, q = 3.0
Also, ScriptingContainer provides better i18n support. For example,
Unicode Escape Sequence can be included in Ruby scripts.
In addition, ScriptingContainer supports a parse-once-eval-many-times feature, invoking methods defined by Ruby, and getting an instance of a specified interface that has been implemented by Ruby.
Example 4:
ScriptingContainer container = new ScriptingContainer();
String script =
"def message\n" +
"\"message: #{@message}\"\n" +
"end\n" +
"message";
container.put("@message", "What's up?");
JavaEmbedUtils.EvalUnit unit = container.parse(script);
IRubyObject msg = unit.run(); // a RubyString instance
System.out.println(JavaEmbedUtils.rubyToJava(msg));
container.put("@message", "Fabulous!");
msg = unit.run();
System.out.println(JavaEmbedUtils.rubyToJava(msg));
container.put("@message", "That's the way you are.");
msg = unit.run();
System.out.println(JavaEmbedUtils.rubyToJava(msg));
Produces:
message: What's up?
message: Fabulous!
message: That's the way you are.
See more details at project's
Wiki| Constructor and Description |
|---|
ScriptingContainer()
Constructs a ScriptingContainer with a default values.
|
ScriptingContainer(LocalContextScope scope)
Constructs a ScriptingContainer with a specified local context type.
|
ScriptingContainer(LocalContextScope scope,
LocalVariableBehavior behavior)
Constructs a ScriptingContainer with a specified local context type and
variable behavior.
|
ScriptingContainer(LocalContextScope scope,
LocalVariableBehavior behavior,
boolean lazy)
Constructs a ScriptingContainer with a specified local context scope,
local variable behavior and laziness.
|
ScriptingContainer(LocalVariableBehavior behavior)
Constructs a ScriptingContainer with a specified local variable behavior.
|
| Modifier and Type | Method and Description |
|---|---|
void |
addGemPath(ClassLoader classloader)
add the given classloader to the GEM_PATH
|
protected void |
addGemPath(String uri) |
void |
addLoadPath(ClassLoader classloader)
add the given classloader to the LOAD_PATH
|
protected void |
addLoadPath(String uri) |
Object |
callMethod(Object receiver,
String methodName,
Block block,
Object... args)
Executes a method defined in Ruby script.
|
<T> T |
callMethod(Object receiver,
String methodName,
Class<T> returnType)
Executes a method defined in Ruby script.
|
<T> T |
callMethod(Object receiver,
String methodName,
Class<T> returnType,
EmbedEvalUnit unit)
Executes a method defined in Ruby script.
|
Object |
callMethod(Object receiver,
String methodName,
Object... args)
Executes a method defined in Ruby script.
|
<T> T |
callMethod(Object receiver,
String methodName,
Object[] args,
Block block,
Class<T> returnType)
Executes a method defined in Ruby script.
|
<T> T |
callMethod(Object receiver,
String methodName,
Object[] args,
Block block,
Class<T> returnType,
EmbedEvalUnit unit)
Executes a method defined in Ruby script.
|
<T> T |
callMethod(Object receiver,
String methodName,
Object[] args,
Class<T> returnType)
Executes a method defined in Ruby script.
|
<T> T |
callMethod(Object receiver,
String methodName,
Object[] args,
Class<T> returnType,
EmbedEvalUnit unit)
Executes a method defined in Ruby script.
|
<T> T |
callMethod(Object receiver,
String methodName,
Object singleArg,
Class<T> returnType)
Executes a method defined in Ruby script.
|
<T> T |
callSuper(Object receiver,
Object[] args,
Block block,
Class<T> returnType) |
<T> T |
callSuper(Object receiver,
Object[] args,
Class<T> returnType) |
void |
clear()
Removes all of the mappings from this map.
|
void |
finalize()
Ensure this ScriptingContainer instance is terminated when nobody holds any
references to it (and GC wants to reclaim it).
|
Object |
get(Object receiver,
String key)
Returns a value of a specified key in a specified receiver or null if
a variable map doesn't have a mapping for the key in a given
receiver.
|
Object |
get(String key)
Returns a value of the specified key in a top level of runtime or null
if this map doesn't have a mapping for the key.
|
String[] |
getArgv()
Returns a list of argument.
|
Object |
getAttribute(Object key)
Returns an attribute value associated with the specified key in
a attribute map.
|
Map |
getAttributeMap()
Returns a attribute map in one of
LocalContextScope. |
ClassLoader |
getClassLoader()
Returns a class loader object that is currently used.
|
boolean |
getClassloaderDelegate()
Retrieve the self-first classloader setting.
|
CompatVersion |
getCompatVersion()
Deprecated.
|
RubyInstanceConfig.CompileMode |
getCompileMode()
Returns a compile mode currently chosen, which is one of CompileMode.JIT,
CompileMode.FORCE, CompileMode.OFF.
|
String |
getCurrentDirectory()
Returns a current directory.
|
Map |
getEnvironment()
Returns a map of environment variables.
|
PrintStream |
getErr()
Deprecated.
As of JRuby 1.5.0, Replaced by getError()
|
PrintStream |
getError()
Returns an error stream assigned to STDERR and $stderr.
|
Writer |
getErrorWriter()
Returns an error writer set in an attribute map.
|
String |
getHomeDirectory()
Returns a JRuby home directory.
|
InputStream |
getIn()
Deprecated.
As of JRuby 1.5.0, replaced by getInput().
|
InputStream |
getInput()
Returns an input stream assigned to STDIN and $stdin.
|
<T> T |
getInstance(Object receiver,
Class<T> clazz)
Returns an instance of a requested interface type.
|
int |
getJitLogEvery()
Returns the value of n, which means that jitted methods are logged in
every n methods.
|
int |
getJitMax()
Returns a value of a max class cache size.
|
int |
getJitMaxSize()
Returns a value of a max size of the bytecode generated by compiler.
|
int |
getJitThreshold()
Returns a value of the threshold that determines whether jitted methods'
call reached to the limit or not.
|
KCode |
getKCode()
Returns a value of KCode currently used.
|
List<String> |
getLoadPaths()
Returns a list of load paths for Ruby scripts/libraries.
|
RubyInstanceConfig.LoadServiceCreator |
getLoadServiceCreator()
Returns a LoadServiceCreator currently used.
|
PrintStream |
getOut()
Deprecated.
As of JRuby 1.5.0, replaced by getOutput().
|
PrintStream |
getOutput()
Returns an output stream assigned to STDOUT and $stdout.
|
Profile |
getProfile()
Returns a Profile currently used.
|
ProfileOutput |
getProfileOutput()
Returns currently configured ProfileOutput object, which determines where
the output of profiling operations will be sent.
|
RubyInstanceConfig.ProfilingMode |
getProfilingMode()
Returns a ProfilingMode currently used.
|
String[] |
getProperty(String key)
Returns an array of values associated to a key.
|
LocalContextProvider |
getProvider()
Returns a provider instance of
LocalContextProvider. |
Reader |
getReader()
Returns a reader set in an attribute map.
|
String |
getRecordSeparator()
Returns a record separator.
|
Ruby |
getRuntime()
Deprecated.
As of JRuby 1.5.0. Use getProvider().getRuntime() method instead.
|
String |
getScriptFilename()
Returns a script filename to run.
|
String |
getSupportedRubyVersion()
Returns version information about JRuby and Ruby supported by this platform.
|
BiVariableMap |
getVarMap()
Returns a variable map in one of
LocalContextScope. |
Writer |
getWriter()
Returns a writer set in an attribute map.
|
boolean |
isNativeEnabled()
Get whether native code is enabled for this config.
|
boolean |
isObjectSpaceEnabled()
Tests whether the Object Space is enabled or not.
|
boolean |
isRunRubyInProcess()
Tests whether Ruby runs in a process or not.
|
EmbedRubyObjectAdapter |
newObjectAdapter()
Returns an instance of
EmbedRubyObjectAdapter for embedders to invoke
methods defined by Ruby. |
EmbedRubyRuntimeAdapter |
newRuntimeAdapter()
Returns an instance of
EmbedRubyRuntimeAdapter for embedders to parse
scripts. |
EmbedEvalUnit |
parse(InputStream istream,
String filename,
int... lines)
Parses a script given by a input stream and return an object which can be run().
|
EmbedEvalUnit |
parse(PathType type,
String filename,
int... lines)
Parses a script read from a specified path and return an object which can be run().
|
EmbedEvalUnit |
parse(Reader reader,
String filename,
int... lines)
Parses a script given by a reader and return an object which can be run().
|
EmbedEvalUnit |
parse(String script,
int... lines)
Parses a script and return an object which can be run().
|
Object |
put(Object receiver,
String key,
Object value)
Associates the specified value with the specified key in a variable map.
|
Object |
put(String key,
Object value)
Associates the specified value with the specified key in a
variable map.
|
Object |
remove(Object receiver,
String key)
Removes the specified Ruby variable with the specified variable name in a
variable map and given receiver.
|
Object |
remove(String key)
Removes the specified Ruby variable with the specified variable name from a
variable map and runtime top level.
|
Object |
removeAttribute(Object key)
Removes the specified value with the specified key in a
attribute map.
|
void |
resetErrorWriter() |
void |
resetWriter() |
<T> T |
runRubyMethod(Class<T> returnType,
Object receiver,
String methodName,
Block block,
Object... args)
Executes a method defined in Ruby script.
|
<T> T |
runRubyMethod(Class<T> returnType,
Object receiver,
String methodName,
Object... args)
Executes a method defined in Ruby script.
|
Object |
runScriptlet(InputStream istream,
String filename)
Evaluates a script read from a input stream under the current scope
(perhaps the top-level scope) and returns a result only if a script
returns a value.
|
Object |
runScriptlet(PathType type,
String filename)
Reads a script file from specified path and evaluates it under the current
scope (perhaps the top-level scope) and returns a result only if a script
returns a value.
|
Object |
runScriptlet(Reader reader,
String filename)
Evaluates a script read from a reader under the current scope
(perhaps the top-level scope) and returns a result only if a script
returns a value.
|
Object |
runScriptlet(String script)
Evaluates a script under the current scope (perhaps the top-level
scope) and returns a result only if a script returns a value.
|
void |
setArgv(String[] argv)
Changes values of the arguments' list.
|
Object |
setAttribute(Object key,
Object value)
Associates the specified value with the specified key in a
attribute map.
|
void |
setClassLoader(ClassLoader loader)
Changes a class loader to a given loader.
|
void |
setClassloaderDelegate(boolean classloaderDelegate)
Force dynamically-loaded Java classes to load first from the classloader provided by
JRuby before searching parent classloaders.
|
void |
setCompatVersion(CompatVersion version)
Deprecated.
|
void |
setCompileMode(RubyInstanceConfig.CompileMode mode)
Changes a compile mode to a given mode, which should be one of CompileMode.JIT,
CompileMode.FORCE, CompileMode.OFF.
|
void |
setCurrentDirectory(String directory)
Changes a current directory to a given directory.
|
void |
setEnvironment(Map environment)
Changes an environment variables' map.
|
void |
setError(PrintStream pstream)
Changes STDERR and $stderr to a given print stream.
|
void |
setError(Writer writer)
Changes STDERR and $stderr to a given writer.
|
void |
setErrorWriter(Writer errorWriter)
Replaces a standard error by a specified writer.
|
void |
setHomeDirectory(String home)
Changes a JRuby home directory to a directory of a given name.
|
void |
setInput(InputStream istream)
Changes STDIN and $stdin to a given input stream.
|
void |
setInput(Reader reader)
Changes STDIN and $stdin to a given reader.
|
void |
setJitLogEvery(int logEvery)
Changes a value of n, so that jitted methods are logged in every n methods.
|
void |
setJitMax(int max)
Changes a value of a max class cache size.
|
void |
setJitMaxSize(int maxSize)
Changes a value of a max size of the bytecode generated by compiler.
|
void |
setJitThreshold(int threshold)
Changes a value of the threshold that determines whether jitted methods'
call reached to the limit or not.
|
void |
setKCode(KCode kcode)
Changes a value of KCode to a given value.
|
void |
setLoadPaths(List<String> paths)
Changes a list of load paths Ruby scripts/libraries.
|
void |
setLoadServiceCreator(RubyInstanceConfig.LoadServiceCreator creator)
Changes a LoadServiceCreator to a given one.
|
void |
setNativeEnabled(boolean b)
Set whether native code is enabled for this config.
|
void |
setObjectSpaceEnabled(boolean enable)
Changes the value to determine whether the Object Space is enabled or not.
|
void |
setOutput(PrintStream pstream)
Changes STDOUT and $stdout to a given output stream.
|
void |
setOutput(Writer writer)
Changes STDOUT and $stdout to a given writer.
|
void |
setProfile(Profile profile)
Changes a Profile to a given one.
|
void |
setProfile(RubyInstanceConfig.ProfilingMode mode)
Deprecated.
Use setProfilingMode instead
|
void |
setProfileOutput(ProfileOutput out)
Changes ProfileOutput to given one.
|
void |
setProfilingMode(RubyInstanceConfig.ProfilingMode mode)
Changes a ProfilingMode to a given one.
|
void |
setReader(Reader reader)
Replaces a standard input by a specified reader
|
void |
setRecordSeparator(String separator)
Changes a record separator to a given value.
|
void |
setRunRubyInProcess(boolean inprocess)
Changes the value to determine whether Ruby runs in a process or not.
|
void |
setScriptFilename(String filename)
Changes a script filename to run.
|
void |
setWriter(Writer writer)
Replaces a standard output by a specified writer.
|
void |
terminate()
Cleanly shut down this ScriptingContainer and any JRuby resources it holds.
|
public ScriptingContainer()
public ScriptingContainer(LocalContextScope scope)
scope - a local context type.public ScriptingContainer(LocalVariableBehavior behavior)
behavior - a local variable behaviorpublic ScriptingContainer(LocalContextScope scope, LocalVariableBehavior behavior)
scope - a local context typebehavior - a local variable behaviorpublic ScriptingContainer(LocalContextScope scope, LocalVariableBehavior behavior, boolean lazy)
scope - is one of a local context scope defined by LocalContextScopebehavior - is one of a local variable behavior defined by LocalVariableBehaviorlazy - is a switch to do lazy retrieval of variables/constants from
Ruby runtime. Default is true. When this value is true, ScriptingContainer tries to
get as many variables/constants as possible from Ruby runtime.public List<String> getLoadPaths()
getLoadPaths in interface EmbedRubyInstanceConfigAdapterpublic void setLoadPaths(List<String> paths)
setLoadPaths in interface EmbedRubyInstanceConfigAdapterpaths - a new list of load paths.public InputStream getInput()
getInput in interface EmbedRubyInstanceConfigAdapterpublic void setInput(InputStream istream)
setInput in interface EmbedRubyInstanceConfigAdapteristream - an input stream to be setpublic void setInput(Reader reader)
setInput in interface EmbedRubyInstanceConfigAdapterreader - a reader to be setpublic PrintStream getOutput()
getOutput in interface EmbedRubyInstanceConfigAdapterpublic void setOutput(PrintStream pstream)
setOutput in interface EmbedRubyInstanceConfigAdapterpstream - an output stream to be setpublic void setOutput(Writer writer)
setOutput in interface EmbedRubyInstanceConfigAdapterwriter - a writer to be setpublic PrintStream getError()
getError in interface EmbedRubyInstanceConfigAdapterpublic void setError(PrintStream pstream)
setError in interface EmbedRubyInstanceConfigAdapterpstream - a print stream to be setpublic void setError(Writer writer)
setError in interface EmbedRubyInstanceConfigAdapterwriter - a writer to be setpublic RubyInstanceConfig.CompileMode getCompileMode()
getCompileMode in interface EmbedRubyInstanceConfigAdapterpublic void setCompileMode(RubyInstanceConfig.CompileMode mode)
setCompileMode in interface EmbedRubyInstanceConfigAdaptermode - compile modepublic boolean isRunRubyInProcess()
isRunRubyInProcess in interface EmbedRubyInstanceConfigAdapterpublic void setRunRubyInProcess(boolean inprocess)
setRunRubyInProcess in interface EmbedRubyInstanceConfigAdapterinprocess - true when Ruby is set to run in the process, or false not to
run in the process.@Deprecated public CompatVersion getCompatVersion()
getCompatVersion in interface EmbedRubyInstanceConfigAdapter@Deprecated public void setCompatVersion(CompatVersion version)
setCompatVersion in interface EmbedRubyInstanceConfigAdapterpublic boolean isObjectSpaceEnabled()
isObjectSpaceEnabled in interface EmbedRubyInstanceConfigAdapterpublic void setObjectSpaceEnabled(boolean enable)
setObjectSpaceEnabled in interface EmbedRubyInstanceConfigAdapterenable - true to enable the Object Space, or false to disable.public Map getEnvironment()
getEnvironment in interface EmbedRubyInstanceConfigAdapterpublic void setEnvironment(Map environment)
setEnvironment in interface EmbedRubyInstanceConfigAdapterenvironment - a new map of environment variables.public String getCurrentDirectory()
getCurrentDirectory in interface EmbedRubyInstanceConfigAdapterpublic void setCurrentDirectory(String directory)
setCurrentDirectory in interface EmbedRubyInstanceConfigAdapterdirectory - a new directory to be set.public String getHomeDirectory()
getHomeDirectory in interface EmbedRubyInstanceConfigAdapterpublic void setHomeDirectory(String home)
setHomeDirectory in interface EmbedRubyInstanceConfigAdapterhome - a name of new JRuby home directory.public ClassLoader getClassLoader()
getClassLoader in interface EmbedRubyInstanceConfigAdapterpublic void setClassLoader(ClassLoader loader)
setClassLoader in interface EmbedRubyInstanceConfigAdapterloader - a new class loader to be set.public Profile getProfile()
getProfile in interface EmbedRubyInstanceConfigAdapterpublic void setProfile(Profile profile)
setProfile in interface EmbedRubyInstanceConfigAdapterprofile - a new profiler to be set.public ProfileOutput getProfileOutput()
public void setProfileOutput(ProfileOutput out)
out - a new ProfileOutput object, to which profiling data should be writtenpublic RubyInstanceConfig.ProfilingMode getProfilingMode()
@Deprecated public void setProfile(RubyInstanceConfig.ProfilingMode mode)
mode - a new profiling mode to be set.public void setProfilingMode(RubyInstanceConfig.ProfilingMode mode)
mode - a new profiling mode to be set.public RubyInstanceConfig.LoadServiceCreator getLoadServiceCreator()
getLoadServiceCreator in interface EmbedRubyInstanceConfigAdapterpublic void setLoadServiceCreator(RubyInstanceConfig.LoadServiceCreator creator)
setLoadServiceCreator in interface EmbedRubyInstanceConfigAdaptercreator - a new LoadServiceCreatorpublic String[] getArgv()
getArgv in interface EmbedRubyInstanceConfigAdapterpublic void setArgv(String[] argv)
setArgv in interface EmbedRubyInstanceConfigAdapterargv - a new arguments' list.public String getScriptFilename()
getScriptFilename in interface EmbedRubyInstanceConfigAdapterpublic void setScriptFilename(String filename)
setScriptFilename in interface EmbedRubyInstanceConfigAdapterfilename - a new script filename.public String getRecordSeparator()
getRecordSeparator in interface EmbedRubyInstanceConfigAdapterpublic void setRecordSeparator(String separator)
setRecordSeparator in interface EmbedRubyInstanceConfigAdapterseparator - a new record separator value, "0" or "777"public KCode getKCode()
getKCode in interface EmbedRubyInstanceConfigAdapterpublic void setKCode(KCode kcode)
setKCode in interface EmbedRubyInstanceConfigAdapterkcode - a new KCode value.public void setNativeEnabled(boolean b)
b - new value indicating whether native code is enabledOptions.NATIVE_ENABLEDpublic boolean isNativeEnabled()
Options.NATIVE_ENABLEDpublic int getJitLogEvery()
getJitLogEvery in interface EmbedRubyInstanceConfigAdapterpublic void setJitLogEvery(int logEvery)
setJitLogEvery in interface EmbedRubyInstanceConfigAdapterlogEvery - a new number of methods.public int getJitThreshold()
getJitThreshold in interface EmbedRubyInstanceConfigAdapterpublic void setJitThreshold(int threshold)
setJitThreshold in interface EmbedRubyInstanceConfigAdapterthreshold - a new value of the threshold.public int getJitMax()
getJitMax in interface EmbedRubyInstanceConfigAdapterpublic void setJitMax(int max)
setJitMax in interface EmbedRubyInstanceConfigAdaptermax - a new value of a max class cache size.public int getJitMaxSize()
getJitMaxSize in interface EmbedRubyInstanceConfigAdapterpublic void setJitMaxSize(int maxSize)
setJitMaxSize in interface EmbedRubyInstanceConfigAdaptermaxSize - a new value of a max size of the bytecode.public String getSupportedRubyVersion()
getSupportedRubyVersion in interface EmbedRubyInstanceConfigAdapterpublic String[] getProperty(String key)
key - is a key in a property filepublic LocalContextProvider getProvider()
LocalContextProvider. When users
want to configure Ruby runtime, they can do by setting class loading paths,
RubyInstanceConfig to the provider before they get Ruby
runtime.LocalContextProvider@Deprecated public Ruby getRuntime()
LocalContextScope.public BiVariableMap getVarMap()
LocalContextScope. Variables
in this map is used to share between Java and Ruby. Map keys are Ruby's
variable names, thus they must be valid Ruby names.public Map getAttributeMap()
LocalContextScope. Attributes
in this map accept any key value pair, types of which are java.lang.Object.
Ruby scripts do not look up this map.public Object getAttribute(Object key)
key - is the attribute keypublic Object setAttribute(Object key, Object value)
key - is a key that the specified value is to be associated withvalue - is a value to be associated with the specified keypublic Object removeAttribute(Object key)
key - is a key that the specified value is to be removed frompublic Object get(String key)
key - is a key whose associated value is to be returnedpublic Object get(Object receiver, String key)
receiver - a receiver to get the value fromkey - is a key whose associated value is to be returnedpublic Object put(String key, Object value)
key - is a key that the specified value is to be associated withvalue - is a value to be associated with the specified keypublic Object put(Object receiver, String key, Object value)
receiver - a receiver to put the value inkey - is a key that the specified value is to be associated withvalue - is a value to be associated with the specified keypublic Object remove(String key)
key - is a key that the specified value is to be associated withpublic Object remove(Object receiver, String key)
receiver - a receiver to remove the value fromkey - is a key that the specified value is to be associated withpublic void clear()
public EmbedEvalUnit parse(String script, int... lines)
script - is a Ruby script to be parsedlines - are linenumbers to display for parse errors and backtraces.
This field is optional. Only the first argument is used for parsing.
When no line number is specified, 0 is applied to.public EmbedEvalUnit parse(Reader reader, String filename, int... lines)
reader - is used to read a script fromfilename - is used as in information, for example, appears in a stack trace
of an exceptionlines - are linenumbers to display for parse errors and backtraces.
This field is optional. Only the first argument is used for parsing.
When no line number is specified, 0 is applied to.public EmbedEvalUnit parse(PathType type, String filename, int... lines)
type - is one of the types PathType definesfilename - is used as in information, for example, appears in a stack trace
of an exceptionlines - are linenumbers to display for parse errors and backtraces.
This field is optional. Only the first argument is used for parsing.
When no line number is specified, 0 is applied to.public EmbedEvalUnit parse(InputStream istream, String filename, int... lines)
istream - is an input stream to get a script fromfilename - filename is used as in information, for example, appears in a stack trace
of an exceptionlines - are linenumbers to display for parse errors and backtraces.
This field is optional. Only the first argument is used for parsing.
When no line number is specified, 0 is applied to.public Object runScriptlet(String script)
script - is a Ruby script to get runpublic Object runScriptlet(Reader reader, String filename)
reader - is used to read a script fromfilename - is used as in information, for example, appears in a stack trace
of an exceptionpublic Object runScriptlet(InputStream istream, String filename)
istream - is used to input a script fromfilename - is used as in information, for example, appears in a stack trace
of an exceptionpublic Object runScriptlet(PathType type, String filename)
type - is one of the types PathType definesfilename - is used to read the script from and an informationpublic EmbedRubyRuntimeAdapter newRuntimeAdapter()
EmbedRubyRuntimeAdapter for embedders to parse
scripts.EmbedRubyRuntimeAdapter.public EmbedRubyObjectAdapter newObjectAdapter()
EmbedRubyObjectAdapter for embedders to invoke
methods defined by Ruby. The script must be evaluated prior to a method call.
In most cases, users don't need to use this method. ScriptingContainer's
callMethods are the shortcut and work in the same way.
Example
# calendar.rb
require 'date'
class Calendar
def initialize;@today = DateTime.now;end
def next_year;@today.year + 1;end
end
Calendar.new
ScriptingContainer container = new ScriptingContainer();
String filename = "ruby/calendar.rb";
Object receiver = instance.runScriptlet(PathType.CLASSPATH, filename);
EmbedRubyObjectAdapter adapter = instance.newObjectAdapter();
Integer result =
(Integer) adapter.callMethod(receiver, "next_year", Integer.class);
System.out.println("next year: " + result);
System.out.println(instance.get("@today"));
Outputs:
next year: 2010
2009-05-19T17:46:44-04:00EmbedRubyObjectAdapterpublic Object callMethod(Object receiver, String methodName, Object... args)
receiver - is an instance that will receive this method call.
Ruby's self object will be used if no appropriate receiver
is given.methodName - is a method name to be calledargs - is an array of method argumentspublic Object callMethod(Object receiver, String methodName, Block block, Object... args)
receiver - is an instance that will receive this method call
Ruby's self object will be used if no appropriate receiver
is given.methodName - is a method name to be calledblock - is a block to be executed in this methodargs - is an array of method argumentspublic <T> T callMethod(Object receiver, String methodName, Class<T> returnType)
receiver - is an instance that will receive this method call.
Ruby's self object will be used if no appropriate receiver
is given.methodName - is a method name to be calledreturnType - is the type we want it to convert topublic <T> T callMethod(Object receiver, String methodName, Object singleArg, Class<T> returnType)
receiver - is an instance that will receive this method call.
Ruby's self object will be used if no appropriate receiver
is given.methodName - is a method name to be calledsingleArg - is an method argumentreturnType - returnType is the type we want it to convert topublic <T> T callMethod(Object receiver, String methodName, Object[] args, Class<T> returnType)
receiver - is an instance that will receive this method call.
Ruby's self object will be used if no appropriate receiver
is given.methodName - is a method name to be calledargs - is an array of method argumentsreturnType - is the type we want it to convert topublic <T> T callMethod(Object receiver, String methodName, Object[] args, Block block, Class<T> returnType)
receiver - is an instance that will receive this method call.
Ruby's self object will be used if no appropriate receiver
is given.methodName - is a method name to be calledargs - is an array of method arguments except a blockblock - is a block to be executed in this methodreturnType - is the type we want it to convert topublic <T> T callMethod(Object receiver, String methodName, Class<T> returnType, EmbedEvalUnit unit)
receiver - is an instance that will receive this method call.
Ruby's self object will be used if no appropriate receiver
is given.methodName - is a method name to be calledreturnType - is the type we want it to convert tounit - is parsed unitpublic <T> T callMethod(Object receiver, String methodName, Object[] args, Class<T> returnType, EmbedEvalUnit unit)
receiver - is an instance that will receive this method call.
Ruby's self object will be used if no appropriate receiver
is given.methodName - is a method name to be calledargs - is an array of method argumentsreturnType - is the type we want it to convert tounit - is parsed unitpublic <T> T callMethod(Object receiver, String methodName, Object[] args, Block block, Class<T> returnType, EmbedEvalUnit unit)
receiver - is an instance that will receive this method call.
Ruby's self object will be used if no appropriate receiver
is given.methodName - is a method name to be calledargs - is an array of method arguments except a blockblock - is a block to be executed in this methodreturnType - is the type we want it to convert tounit - is parsed unitpublic <T> T callSuper(Object receiver, Object[] args, Class<T> returnType)
receiver - is an instance that will receive this method call.
Ruby's self object will be used if no appropriate receiver
is given.args - is an array of method argumentsreturnType - is the type we want it to convert topublic <T> T callSuper(Object receiver, Object[] args, Block block, Class<T> returnType)
receiver - is an instance that will receive this method call.
Ruby's self object will be used if no appropriate receiver
is given.args - is an array of method arguments except a blockblock - is a block to be executed in this methodreturnType - is the type we want it to convert topublic <T> T runRubyMethod(Class<T> returnType, Object receiver, String methodName, Object... args)
returnType - is the type we want it to convert toreceiver - is an instance that will receive this method call. The receiver
can be null or other Java objects as well as RubyObject.
The null will be converted to RubyNil. Java objects will be
wrapped in RubyObject.methodName - is a method name to be calledargs - is an array of method argumentspublic <T> T runRubyMethod(Class<T> returnType, Object receiver, String methodName, Block block, Object... args)
returnType - is the type we want it to convert toreceiver - is an instance that will receive this method call. The receiver
can be null or other Java objects as well as RubyObject.
The null will be converted to RubyNil. Java objects will be
wrapped in RubyObject.methodName - is a method name to be calledblock - is an optional Block object. Send null for no block.args - is an array of method argumentspublic <T> T getInstance(Object receiver, Class<T> clazz)
Example
Interface
//QuadraticFormula.java
package org.jruby.embed;
import java.util.List;
public interface QuadraticFormula {
List solve(int a, int b, int c) throws Exception;
}
Implementation
#quadratic_formula.rb
def solve(a, b, c)
v = b ** 2 - 4 * a * c
if v < 0: raise RangeError end
s0 = ((-1)*b - Math.sqrt(v))/(2*a)
s1 = ((-1)*b + Math.sqrt(v))/(2*a)
return s0, s1
end
Usage
ScriptingContainer container = new ScriptingContainer();
String filename = "ruby/quadratic_formula_class.rb";
Object receiver = container.runScriptlet(PathType.CLASSPATH, filename);
QuadraticFormula qf = container.getInstance(receiver, QuadraticFormula.class);
try {
List solutions = qf.solve(1, -2, -13);
printSolutions(solutions);
solutions = qf.solve(1, -2, 13);
for (double s : solutions) {
System.out.print(s + ", ");
}
} catch (Exception e) {
e.printStackTrace();
}
Output
-2.7416573867739413, 4.741657386773941,
receiver - is an instance that implements the interfaceclazz - is a requested interfacepublic void setReader(Reader reader)
reader - is a reader to be setpublic Reader getReader()
@Deprecated public InputStream getIn()
public void setWriter(Writer writer)
writer - is a writer to be setpublic void resetWriter()
public Writer getWriter()
@Deprecated public PrintStream getOut()
public void setErrorWriter(Writer errorWriter)
errorWriter - is a writer to be setpublic void resetErrorWriter()
public Writer getErrorWriter()
@Deprecated public PrintStream getErr()
public void terminate()
public void finalize()
throws Throwable
org.jruby.embed.LocalContextScope::SINGLETON containers will not terminate on GC.public void setClassloaderDelegate(boolean classloaderDelegate)
classloaderDelegate - set whether prefer the JRuby classloader to delegate first
to the parent classloader when dynamically loading classespublic boolean getClassloaderDelegate()
setClassloaderDelegate(boolean)public void addLoadPath(ClassLoader classloader)
classloader - protected void addLoadPath(String uri)
public void addGemPath(ClassLoader classloader)
classloader - protected void addGemPath(String uri)
Copyright © 2001-2015 JRuby. All Rights Reserved.