javascriptrubyopalrbopal

Cannot use Ruby Math library with Opal


Is there a way to use the ruby Math library in Opal ?

I got the following error message Uncaught NameError: uninitialized constant Object::Math when using Math::PI in my ruby method.

The ruby code :

class Numeric
  def degrees
    self * Math::PI / 180 
  end
end

The generated javascript by Opal :

/* Generated by Opal 0.6.3 */
(function($opal) {
  var self = $opal.top, $scope = $opal, nil = $opal.nil, $breaker = $opal.breaker, $slice = $opal.slice, $klass = $opal.klass;

  $opal.add_stubs(['$/', '$*']);
  return (function($base, $super) {
    function $Numeric(){};
    var self = $Numeric = $klass($base, $super, 'Numeric', $Numeric);

    var def = self._proto, $scope = self._scope;

    return (def.$degrees = function() {
      var $a, $b, self = this;

      return self['$*']((($a = ((($b = $scope.Math) == null ? $opal.cm('Math') : $b))._scope).PI == null ? $a.cm('PI') : $a.PI))['$/'](180);
    }, nil) && 'degrees'
  })(self, null)
})(Opal);

//# sourceMappingURL=/__opal_source_maps__/game_engine/numeric.js.map
;

Thanks ;)


Solution

  • The Math module is in Opal's stdlib and isn't included in the default runtime (as far as I can tell).

    Depending on your deployment context, it might be easiest to build the Math module (Opal::Builder.build('math')) into a file.

    For your specific example, though, you can just use the JS PI approximation (which is all that Opal's Math::PI does anyway):

    class Numeric
      def degrees
        self * `Math.PI` / 180 
      end
    end