Add ability to load JS files from classpath
This will allow better packaging of the resources needed to run the tests.
This commit is contained in:
parent
7b8d034d48
commit
1583ec50ce
|
@ -1,5 +1,7 @@
|
|||
package be.klak.rhino;
|
||||
|
||||
import java.net.URL;
|
||||
|
||||
import org.mozilla.javascript.Context;
|
||||
import org.mozilla.javascript.ContextFactory;
|
||||
import org.mozilla.javascript.Function;
|
||||
|
@ -86,6 +88,24 @@ public class RhinoContext {
|
|||
// Main.processFile(this.jsContext, this.jsScope, fileName);
|
||||
}
|
||||
|
||||
// {{{ loadFromClasspath
|
||||
/**
|
||||
* Loads a resource from the classpath.
|
||||
*
|
||||
* @param resource the resource to resolve from the classpath
|
||||
*/
|
||||
public void loadFromClasspath(final String resource) {
|
||||
URL rsrcUrl =
|
||||
Thread.currentThread().getContextClassLoader().getResource(resource);
|
||||
|
||||
if (rsrcUrl == null) {
|
||||
throw new IllegalArgumentException("resource " + resource + " not found on classpath");
|
||||
}
|
||||
|
||||
evalJS(String.format("load('%s')", rsrcUrl.toExternalForm()));
|
||||
}
|
||||
// }}}
|
||||
|
||||
public Object executeFunction(ScriptableObject object, String fnName, Object[] arguments) {
|
||||
Object fnPointer = object.get(fnName, object);
|
||||
if (fnPointer == null || !(fnPointer instanceof Function)) {
|
||||
|
|
|
@ -80,4 +80,14 @@ public class RhinoContextTest {
|
|||
assertThat(context.evalJS("loaded")).isEqualTo(true);
|
||||
assertThat(context.evalJS("loadedTwo")).isEqualTo(true);
|
||||
}
|
||||
|
||||
// {{{ loadsJSFilesFromClasspath
|
||||
@Test
|
||||
public void loadsJSFilesFromClasspath() {
|
||||
RhinoContext context = new RhinoContext();
|
||||
context.loadFromClasspath("js/lib/loadsJSFilesFromClasspathTarget.js");
|
||||
|
||||
assertThat(context.evalJS("target.theAnswer")).isEqualTo("forty two");
|
||||
}
|
||||
// }}}
|
||||
}
|
||||
|
|
Reference in New Issue