I am trying to eval javascript in ruby.
config/initializer/initializer_context.rb
js_str =
EXEC_PP_CONTEXT = ExecJS.compile("function test_add(param) { return param.a+ param.b;}")
and then in my controller I am using :
data_hash = {:a=>4,:b=>5}
EXEC_PP_CONTEXT.exec("return test_add(#{data_hash.to_json})")
But I occasionally get this error ( 1 in 100 requests)
can not use Context instance already associated with some thread
Stack:
If I am already setting max runtime and min runtime to 1 shouldn't it avoid this problem in first place ?
finally figured out by reading Mozilla rhino's code: https://github.com/matthieu/rhymeno/blob/master/src/org/mozilla/javascript/Context.java#LC416
static final Context enter(Context cx, ContextFactory factory)
Basically the method counts the number of threads that are inside the context ( using it / executing it) and if another thread tries to enter it , it throws an error.
To avoid the problem and achieve concurrency , we lazily created one context per thread using ruby's Thread[:current][:some_js_context] = blah_