import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
private final JRubyScriptEngineConfiguration configuration = new JRubyScriptEngineConfiguration();
- // Filter out the File entry to prevent shadowing the Ruby File class which breaks Ruby in spectacularly
- // difficult ways to debug.
- private static final Set<String> FILTERED_PRESETS = Set.of("File", "Files", "Path", "Paths");
- private static final Set<String> INSTANCE_PRESETS = Set.of();
-
private final javax.script.ScriptEngineFactory factory = new org.jruby.embed.jsr223.JRubyEngineFactory();
private final List<String> scriptTypes = Stream
.concat(factory.getExtensions().stream(), factory.getMimeTypes().stream())
.collect(Collectors.toUnmodifiableList());
- // Adds @ in front of a set of variables so that Ruby recognizes them as instance variables
- private static Map.Entry<String, Object> mapInstancePresets(Map.Entry<String, Object> entry) {
- if (INSTANCE_PRESETS.contains(entry.getKey())) {
- return Map.entry("@" + entry.getKey(), entry.getValue());
- } else {
- return entry;
- }
- }
-
// Adds $ in front of a set of variables so that Ruby recognizes them as global variables
private static Map.Entry<String, Object> mapGlobalPresets(Map.Entry<String, Object> entry) {
if (Character.isLowerCase(entry.getKey().charAt(0)) && !(entry.getValue() instanceof Class)
scopeValues //
.entrySet() //
.stream() //
- .filter(map -> !FILTERED_PRESETS.contains(map.getKey())) //
- .map(JRubyScriptEngineFactory::mapInstancePresets) //
.map(JRubyScriptEngineFactory::mapGlobalPresets) //
.collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())); //
private void importClassesToRuby(ScriptEngine scriptEngine, Map<String, Object> objects) {
try {
scriptEngine.put("__classes", objects);
- final String code = "__classes.each { |(name, klass)| Object.const_set(name, klass.ruby_class) }";
+ final String code = "__classes.each { |(name, klass)| Object.const_set(name, klass.ruby_class) unless Object.const_defined?(name, false) }";
scriptEngine.eval(code);
// clean up our temporary variable
scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).remove("__classes");