jruby / jruby

JRuby, an implementation of Ruby on the JVM
https://www.jruby.org
Other
3.77k stars 918 forks source link

system property to automatically prefix variables with @ to become (global) instance variables for jsr223 embedding #7319

Open ccutrer opened 1 year ago

ccutrer commented 1 year ago

Originally from https://github.com/jruby/jruby/issues/5876#issuecomment-1216763407. This is a workaround for the inability for pre-compilation to know if a reference is a variable or a method call when the variables haven't been provided yet.

-Djruby.js223.bindings.localinstancevars=true Java:

...
final ScriptEngine engine = compiledScript.getEngine();
final ScriptContext ctx = engine.getContext();
ctx.setAttribute("input", source_value, ScriptContext.ENGINE_SCOPE);
Object result = compiledScript.eval();

Ruby:

directions = %w[N NE E SE S SW W NW N].freeze

# note that the script uses `@input`, even though the Java
# supplied `input`
if @input == "NULL" || @input == "UNDEF"
  "-"
else
  cardinal = directions[(@input.to_f / 45).round]
  "#{cardinal} (#{@input.to_i}°)"
end

It's up to the user to know to adjust their scripts when setting that property. This avoids having to parse and adjust the actual script, which as you pointed out could be problematic.

enebo commented 1 year ago

@headius I think this is reasonable and this is not the first time people have been messed up with JSR223 attribute bindings.

The only downside of this is assumption that a snippet used by JSR223 in one use will behave the same in another. I don't actually think this is realistic but I just bring it up. I guess the scenario is someone will read a blog post and copy/paste some code and it will not behave as expected. This is just me brainstorming problems.