Module: Wcl::Callback
- Defined in:
- lib/wcl/callback.rb
Overview
Thread-local callback bridge for custom functions invoked from WASM.
Class Method Summary collapse
- .clear_functions ⇒ Object
- .invoke(name, args_json) ⇒ Object
- .json_to_ruby(val) ⇒ Object
- .ruby_to_json(val) ⇒ Object
- .set_functions(fn_hash) ⇒ Object
Class Method Details
.clear_functions ⇒ Object
12 13 14 |
# File 'lib/wcl/callback.rb', line 12 def clear_functions Thread.current[:wcl_functions] = nil end |
.invoke(name, args_json) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/wcl/callback.rb', line 16 def invoke(name, args_json) functions = Thread.current[:wcl_functions] return [false, "callback not found: #{name}"] if functions.nil? || !functions.key?(name) begin args = JSON.parse(args_json) ruby_args = args.map { |a| json_to_ruby(a) } result = functions[name].call(ruby_args) result_json = JSON.generate(ruby_to_json(result)) [true, result_json] rescue => e [false, e.] end end |
.json_to_ruby(val) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/wcl/callback.rb', line 31 def json_to_ruby(val) case val when nil, true, false, Integer, Float, String val when Array val.map { |v| json_to_ruby(v) } when Hash val.transform_values { |v| json_to_ruby(v) } else val end end |
.ruby_to_json(val) ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/wcl/callback.rb', line 44 def ruby_to_json(val) case val when nil, true, false, Integer, Float, String val when Array val.map { |v| ruby_to_json(v) } when Hash val.transform_values { |v| ruby_to_json(v) } when Set { "__type" => "set", "items" => val.map { |v| ruby_to_json(v) } } else val end end |
.set_functions(fn_hash) ⇒ Object
8 9 10 |
# File 'lib/wcl/callback.rb', line 8 def set_functions(fn_hash) Thread.current[:wcl_functions] = fn_hash end |