diff --git a/README.rdoc b/README.rdoc index 071ea16..45eef61 100644 --- a/README.rdoc +++ b/README.rdoc @@ -22,16 +22,13 @@ Embed the Mozilla Rhino Javascript interpreter into Ruby # evaluate some simple javascript eval_js "7 * 6" #=> 42 -# evaluate bytes read from any File/IO object: - File.open("mysource.js") do |file| - eval_js file, "mysource.js" - - #or in the context of a controlled scope - Rhino::Context.open do |context| - context['foo'] = 'some global variable referenced in mysource.js' - context.eval(file, "mysource.js") +# that's quick and dirty, but if you want more control over your +# environment, use a Context: + Rhino::Context.open do |cxt| + cxt['foo'] = "bar" + cxt.eval('foo') # => "bar" end - + # evaluate a ruby function from javascript Rhino::Context.open do |context| @@ -73,6 +70,21 @@ Embed the Mozilla Rhino Javascript interpreter into Ruby Rhino::Context.open(:java => true) do |context| context.eval("java.lang.System.exit()") #it's dangerous! end + +==== Different ways of loading javascript source + +In addition to just evaluating strings, you can also use streams such as files. + +# evaluate bytes read from any File/IO object: + File.open("mysource.js") do |file| + eval_js file, "mysource.js" + end + +# or load it by filename + Rhino::Context.open do |context| + context.load("mysource.js") + end + == REQUIREMENTS: diff --git a/lib/rhino/context.rb b/lib/rhino/context.rb index 3b22844..034b4cc 100644 --- a/lib/rhino/context.rb +++ b/lib/rhino/context.rb @@ -92,7 +92,20 @@ def eval(source, source_name = "", line_number = 1) raise Rhino::RhinoError, e end end - + + # Read the contents of filename and evaluate it as javascript. Returns the result of evaluating the + # javascript. e.g. + # + # Context.open do |cxt| + # cxt.load("path/to/some/lib.js") + # end + # + def load(filename) + File.open(filename) do |file| + eval file, filename, 1 + end + end + # Set the maximum number of instructions that this context will execute. # If this instruction limit is exceeded, then a Rhino::RunawayScriptError # will be raised diff --git a/spec/rhino/context_spec.rb b/spec/rhino/context_spec.rb index 6b83491..0ab9275 100644 --- a/spec/rhino/context_spec.rb +++ b/spec/rhino/context_spec.rb @@ -124,7 +124,7 @@ def timesfive(rhs) }.should raise_error end - describe "compilation" do + describe "loading javascript source into the interpreter" do it "can take an IO object in the eval method instead of a string" do source = StringIO.new(<<-EOJS) @@ -147,5 +147,16 @@ def timesfive(rhs) end end + it "can load a file into the runtime" do + mock(:JavascriptSourceFile).tap do |file| + File.should_receive(:open).with("path/to/mysource.js").and_yield(file) + Context.open do |cxt| + cxt.should_receive(:eval).with(file, "path/to/mysource.js", 1) + cxt.load("path/to/mysource.js") + end + end + + end + end end \ No newline at end of file