Support globals in Quickjs.eval_code - #64
Conversation
Allow callers to expose Ruby values as JavaScript globals through the globals option. Reuse the native Ruby-to-JavaScript converter so values do not need to be interpolated into generated source.
64f8bff to
acd155a
Compare
|
Thanks for the PR, and for covering docs, RBS and tests. It's a real gap. My own README examples interpolate values into JS source, so this is on me to solve. I'd like to get the shape right first though, because "globals" turns out to be ambiguous here: vm.eval_code('globalThis.a = 1;') # what this PR does
vm.eval_code('let a = 2; a') #=> 2
vm.eval_code('globalThis.a') #=> 1Two live values under one name. Related: the injected value is a one-time copy, though Works today
vm.define_function('a') { 1 }
vm.define_function('b') { 2 }
vm.eval_code('a() + b()') #=> 3
vm.define_function('user') { user } # returns go through the same converter
vm.eval_code('user().name') #=> "Itadori", and stays live if you mutate `user`For JS you don't control that expects the global to exist already, pin it once at setup and leave the JS untouched: vm.eval_code('globalThis.user = user();')The gap that leaves is one-shot I'm still doodling ideal APIs. I'll open a PR and link it here, feedback welcome when I do. |
Summary
globals:option toQuickjs.eval_codeandQuickjs::VM.newWhy
Callers currently need to interpolate values into JavaScript source. Native variable injection provides a concise API without generating a JavaScript wrapper or changing QuickJS core:
The values are installed on the new VM's global object during native initialization, before the code is evaluated.
Validation
bundle exec rake