Skip to content

Instantly share code, notes, and snippets.

@biilmann
Created May 5, 2011 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biilmann/957599 to your computer and use it in GitHub Desktop.
Save biilmann/957599 to your computer and use it in GitHub Desktop.
JRuby - Rhino
# This is enough to get going
require 'java'
require 'vendor/rhino'
module JS
include_package 'org.mozilla.javascript'
end
context = JS::Context.enter
scope = context.initStandardObjects
code = %[
var javascriptInMyJavaInMyRuby = function() {
return "Can you say polyglot programming?!";
};
javascriptInMyJavaInMyRuby();
]
puts context.evaluateString(scope, code, "example-1.js", 1, nil)
# Limiting resource use
require 'java'
require 'vendor/rhino'
module JS
include_package 'org.mozilla.javascript'
class RestrictedContext < JS::Context
attr_accessor :start_time, :instruction_count
end
class RestrictedContextFactory < JS::ContextFactory
INSTRUCTION_LIMIT = 1000
TIME_LIMIT = 1
def self.restrict(context)
context.language_version = JS::Context::VERSION_1_8
context.instruction_observer_threshold = 100
context.optimization_level = -1
end
def restrict(context)
self.class.restrict(context)
end
def makeContext
RestrictedContext.new.tap do |context|
restrict(context)
end
end
def observeInstructionCount(context, instruction_count)
context.instruction_count += instruction_count
if context.instruction_count > INSTRUCTION_LIMIT || (Time.now - context.start_time).to_i > TIME_LIMIT
raise "Yikes! Wayyyy too many instructions for me!"
end
end
def doTopCall(callable, context, scope, this_obj, args)
context.start_time = Time.now
context.instruction_count = 0
super
end
end
end
JS::ContextFactory.initGlobal(JS::RestrictedContextFactory.new)
context = JS::Context.enter
scope = context.initStandardObjects
code = %[
var javascriptInMyJavaInMyRuby = function() {
return "Can you say polyglot programming?!";
};
while (true) {
// HAHA
}
javascriptInMyJavaInMyRuby();
]
puts context.evaluateString(scope, code, "example-2.js", 1, nil)
# Exposing Ruby methods
require 'java'
require 'vendor/rhino'
require 'net/http'
module JS
include_package 'org.mozilla.javascript'
class HttpFunction < JS::NativeFunction
def call(context, scope, scriptable, args)
Net::HTTP.get URI.parse(args[0])
end
end
end
context = JS::Context.enter
scope = context.initStandardObjects
JS::ScriptableObject.putProperty(scope, "http", JS::HttpFunction.new)
code = %[
http("http://www.webpop.com")
]
puts context.evaluateString(scope, code, "example-3.js", 1, nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment