opalrb

Opal file called from client via getsctipt (or xhr'ed and evaled) can't be evaled and used


I want to xhr some opal script, and use ruby code defined there. I tried to get it with $.getScript. But no success for me.

$.ajax({
  url: 'assets/foo.js.rb',
  success: function(data){
    #{ClassInFooJs.new}
  },
  dataType: "script"
});

Moreover the script is evaled (in strange manner), I mean I can call Opal.modules["file_i_required"] from console, and it will return basically the compiled code.

BUT inside of it nothing is evaled, (no console.logs, window["foos"] = #{something}), and I can't reference anything from that file.

Any help?


Solution

  • You should use either require "foo" from Opal or Opal.require("foo") from JavaScript. If the load "foo" behavior is required should be noted that Opal.load("foo") is also present.

    The alternative is to compile files on the server with the :requirable flag set to false but that's kinda difficult unless you compile manually. See the API docs for more info.

    Calling directly Opal.modules["foo"](Opal) should be avoided as it doesn't properly update $LOADED_FEATURES and in general can change in the future.