简体   繁体   中英

How can I check whether a JRuby script defines a particular method?

I'm embedding Ruby within a Java app via JRuby, and need to test whether a given Ruby script defines various methods. I have a very simple JRuby setup:

ScriptingContainer container = new ScriptingContainer();
Object receiver = container.runScriptlet(new FileReader(SCRIPT_PATH));

where SCRIPT_PATH is a File with these contents:

def processDoc(doc)
  return doc
end

I now want to determine whether the script defined the processDoc method, but can't find a way other than actually invoking processDoc , which I'd prefer to avoid. I've tried respond_to? 'processDoc' respond_to? 'processDoc' and methods.include? 'processDoc' methods.include? 'processDoc' , neither of which works, as the following successful set of assertions indicates:

Object doc = new Object();
assert container.runScriptlet("respond_to? :processDoc") == Boolean.FALSE;
assert container.runScriptlet("methods().include? 'processDoc'") == Boolean.FALSE;
assert receiver == null;
assert container.callMethod(receiver, "processDoc", doc) == doc;

Are there any other techniques I can use to determine if a simple JRuby script defines a method with a particular name, without actually invoking the method?

When defining a global method, it becomes a private method of Object . You must therefore use the include_all parameter for respond_to? to get this to work:

container.runScriptlet("Object::respond_to?(:processDoc, true)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM