LoginSignup
12
15

More than 5 years have passed since last update.

OpalでRubyをJavaScriptにコンパイルする

Last updated at Posted at 2016-10-11

opalコマンドは、通常RubyのスクリプトをJavaScriptに変換し、実行まで行います。

$ cat test.rb
p "hello"
$ opal test.rb
"hello"

Rubyスクリプトを実行せずに、JavaScriptに変換する場合には、-cオプションをつけます。

$ opal -c test.rb
(function(undefined) {
  // @note
  //   A few conventions for the documentation of this file:
  //   1. Always use "//" (in contrast with "/**/")
  //   2. The syntax used is Yardoc (yardoc.org), which is intended for Ruby (se below)
  //   3. `@param` and `@return` types should be preceded by `JS.` when referring to
  //      JavaScript constructors (e.g. `JS.Function`) otherwise Ruby is assumed.
  //   4. `nil` and `null` being unambiguous refer to the respective
  //      objects/values in Ruby and JavaScript
  //   5. This is still WIP :) so please give feedback and suggestions on how
  //      to improve or for alternative solutions
  //
  //   The way the code is digested before going through Yardoc is a secret kept
  //   in the docs repo (https://github.com/opal/docs/tree/master).

  if (typeof(this.Opal) !== 'undefined') {
    console.warn('Opal already loaded. Loading twice can cause troubles, please fix your setup.');
    return this.Opal;
  }

  var nil;

  // The actual class for BasicObject
  var BasicObject;
(以下略)

最初の部分はOpal本体で、末尾に変換したRubyスクリプトが続きます。変換スクリプトのみを出力するには、-Oオプションも追加します。

$ opal -cO test.rb
/* Generated by Opal 0.10.2 */
(function(Opal) {
  var self = Opal.top, $scope = Opal, nil = Opal.nil, $breaker = Opal.breaker, $slice = Opal.slice;

  Opal.add_stubs(['$p']);
  return self.$p("hello")
})(Opal);

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

  Opal.add_stubs(['$exit']);
  return $scope.get('Kernel').$exit()
})(Opal);

/* Generated by Opal 0.10.2 */が2つあり、2つの無名関数が出力されています。後者の方は雰囲気的にKernel.exit()のようなものを実行しているように見えます。これはopalがあえて追加しているもので、これを削るには-Eオプションをさらに追加します。

$ opal -cOE test.rb
/* Generated by Opal 0.10.2 */
(function(Opal) {
  var self = Opal.top, $scope = Opal, nil = Opal.nil, $breaker = Opal.breaker, $slice = Opal.slice;

  Opal.add_stubs(['$p']);
  return self.$p("hello")
})(Opal);

これで必要最低限のコードのみ出力されるようになります。

なお、method_missingを使っていない場合は、-Mオプションを追加するともっと短くなります。

$ opal -cOEM test.rb
/* Generated by Opal 0.10.2 */
(function(Opal) {
  var self = Opal.top, $scope = Opal, nil = Opal.nil, $breaker = Opal.breaker, $slice = Opal.slice;

  return self.$p("hello")
})(Opal);
12
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
15