Module: Kernel

Defined in:
opal/opal/corelib/kernel.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, *args, &block) ⇒ Object

Raises:



2
3
4
# File 'opal/opal/corelib/kernel.rb', line 2

def method_missing(symbol, *args, &block)
  raise NoMethodError, "undefined method `#{symbol}' for #{inspect}"
end

Instance Method Details

#<=>(other) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'opal/opal/corelib/kernel.rb', line 14

def <=>(other)
  %x{
    if (#{self == other}) {
      return 0;
    }

    return nil;
  }
end

#===(other) ⇒ Object



10
11
12
# File 'opal/opal/corelib/kernel.rb', line 10

def ===(other)
  self == other
end

#=~(obj) ⇒ Object



6
7
8
# File 'opal/opal/corelib/kernel.rb', line 6

def =~(obj)
  false
end

#Array(object, *args, &block) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'opal/opal/corelib/kernel.rb', line 57

def Array(object, *args, &block)
  %x{
    if (object == null || object === nil) {
      return [];
    }
    else if (#{object.respond_to? :to_ary}) {
      return #{object.to_ary};
    }
    else if (#{object.respond_to? :to_a}) {
      return #{object.to_a};
    }
    else {
      return [object];
    }
  }
end

#callerObject

Opal does not support #caller, but we stub it as an empty array to not break dependant libs



76
77
78
# File 'opal/opal/corelib/kernel.rb', line 76

def caller
  []
end

#classObject



80
81
82
# File 'opal/opal/corelib/kernel.rb', line 80

def class
  `self._klass`
end

#cloneObject



96
97
98
99
100
101
102
103
# File 'opal/opal/corelib/kernel.rb', line 96

def clone
  copy = self.class.allocate

  copy.copy_instance_variables(self)
  copy.initialize_clone(self)

  copy
end

#copy_instance_variables(other) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
# File 'opal/opal/corelib/kernel.rb', line 84

def copy_instance_variables(other)
  %x{
    for (var name in other) {
      if (name.charAt(0) !== '$') {
        if (name !== '_id' && name !== '_klass') {
          self[name] = other[name];
        }
      }
    }
  }
end

#define_singleton_method(name, &body) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'opal/opal/corelib/kernel.rb', line 109

def define_singleton_method(name, &body)
  unless body
    raise ArgumentError, "tried to create Proc object without a block"
  end

  %x{
    var jsid   = '$' + name;
    body._jsid = name;
    body._s    = null;
    body._def  = body;

    #{singleton_class}._proto[jsid] = body;

    return self;
  }
end

#dupObject



126
127
128
129
130
131
132
133
# File 'opal/opal/corelib/kernel.rb', line 126

def dup
  copy = self.class.allocate

  copy.copy_instance_variables(self)
  copy.initialize_dup(self)

  copy
end

#enum_for(method = :each, *args, &block) ⇒ Object Also known as: to_enum



139
140
141
# File 'opal/opal/corelib/kernel.rb', line 139

def enum_for(method = :each, *args, &block)
  Enumerator.for(self, method, *args, &block)
end

#equal?(other) ⇒ Boolean

Returns:



145
146
147
# File 'opal/opal/corelib/kernel.rb', line 145

def equal?(other)
  `self === other`
end

#extend(*mods) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'opal/opal/corelib/kernel.rb', line 149

def extend(*mods)
  %x{
    var singleton = #{singleton_class};

    for (var i = mods.length - 1; i >= 0; i--) {
      var mod = mods[i];

      #{`mod`.append_features `singleton`};
      #{`mod`.extended self};
    }
  }

  self
end

#Float(value) ⇒ Object



378
379
380
381
382
383
384
385
386
# File 'opal/opal/corelib/kernel.rb', line 378

def Float(value)
  if String === value
    `parseFloat(value)`
  elsif value.respond_to? :to_f
    value.to_f
  else
    raise TypeError, "can't convert #{value.class} into Float"
  end
end

#format(format, *args) ⇒ Object Also known as: sprintf



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'opal/opal/corelib/kernel.rb', line 164

def format(format, *args)
  %x{
    var idx = 0;
    return format.replace(/%(\d+\$)?([-+ 0]*)(\d*|\*(\d+\$)?)(?:\.(\d*|\*(\d+\$)?))?([cspdiubBoxXfgeEG])|(%%)/g, function(str, idx_str, flags, width_str, w_idx_str, prec_str, p_idx_str, spec, escaped) {
      if (escaped) {
        return '%';
      }

      var width,
      prec,
      is_integer_spec = ("diubBoxX".indexOf(spec) != -1),
      is_float_spec = ("eEfgG".indexOf(spec) != -1),
      prefix = '',
      obj;

      if (width_str === undefined) {
        width = undefined;
      } else if (width_str.charAt(0) == '*') {
        var w_idx = idx++;
        if (w_idx_str) {
          w_idx = parseInt(w_idx_str, 10) - 1;
        }
        width = #{`args[w_idx]`.to_i};
      } else {
        width = parseInt(width_str, 10);
      }
      if (!prec_str) {
        prec = is_float_spec ? 6 : undefined;
      } else if (prec_str.charAt(0) == '*') {
        var p_idx = idx++;
        if (p_idx_str) {
          p_idx = parseInt(p_idx_str, 10) - 1;
        }
        prec = #{`args[p_idx]`.to_i};
      } else {
        prec = parseInt(prec_str, 10);
      }
      if (idx_str) {
        idx = parseInt(idx_str, 10) - 1;
      }
      switch (spec) {
      case 'c':
        obj = args[idx];
        if (obj._isString) {
          str = obj.charAt(0);
        } else {
          str = String.fromCharCode(#{`obj`.to_i});
        }
        break;
      case 's':
        str = #{`args[idx]`.to_s};
        if (prec !== undefined) {
          str = str.substr(0, prec);
        }
        break;
      case 'p':
        str = #{`args[idx]`.inspect};
        if (prec !== undefined) {
          str = str.substr(0, prec);
        }
        break;
      case 'd':
      case 'i':
      case 'u':
        str = #{`args[idx]`.to_i}.toString();
        break;
      case 'b':
      case 'B':
        str = #{`args[idx]`.to_i}.toString(2);
        break;
      case 'o':
        str = #{`args[idx]`.to_i}.toString(8);
        break;
      case 'x':
      case 'X':
        str = #{`args[idx]`.to_i}.toString(16);
        break;
      case 'e':
      case 'E':
        str = #{`args[idx]`.to_f}.toExponential(prec);
        break;
      case 'f':
        str = #{`args[idx]`.to_f}.toFixed(prec);
        break;
      case 'g':
      case 'G':
        str = #{`args[idx]`.to_f}.toPrecision(prec);
        break;
      }
      idx++;
      if (is_integer_spec || is_float_spec) {
        if (str.charAt(0) == '-') {
          prefix = '-';
          str = str.substr(1);
        } else {
          if (flags.indexOf('+') != -1) {
            prefix = '+';
          } else if (flags.indexOf(' ') != -1) {
            prefix = ' ';
          }
        }
      }
      if (is_integer_spec && prec !== undefined) {
        if (str.length < prec) {
          str = #{'0' * `prec - str.length`} + str;
        }
      }
      var total_len = prefix.length + str.length;
      if (width !== undefined && total_len < width) {
        if (flags.indexOf('-') != -1) {
          str = str + #{' ' * `width - total_len`};
        } else {
          var pad_char = ' ';
          if (flags.indexOf('0') != -1) {
            str = #{'0' * `width - total_len`} + str;
          } else {
            prefix = #{' ' * `width - total_len`} + prefix;
          }
        }
      }
      var result = prefix + str;
      if ('XEG'.indexOf(spec) != -1) {
        result = result.toUpperCase();
      }
      return result;
    });
  }
end

#freezeObject



581
582
583
584
# File 'opal/opal/corelib/kernel.rb', line 581

def freeze
  @___frozen___ = true
  self
end

#frozen?Boolean

Returns:



586
587
588
# File 'opal/opal/corelib/kernel.rb', line 586

def frozen?
  @___frozen___ || false
end

#hashObject



293
294
295
# File 'opal/opal/corelib/kernel.rb', line 293

def hash
  `self._id`
end

#initialize_clone(other) ⇒ Object



105
106
107
# File 'opal/opal/corelib/kernel.rb', line 105

def initialize_clone(other)
  initialize_copy(other)
end

#initialize_copy(other) ⇒ Object



297
298
# File 'opal/opal/corelib/kernel.rb', line 297

def initialize_copy(other)
end

#initialize_dup(other) ⇒ Object



135
136
137
# File 'opal/opal/corelib/kernel.rb', line 135

def initialize_dup(other)
  initialize_copy(other)
end

#inspectObject



300
301
302
# File 'opal/opal/corelib/kernel.rb', line 300

def inspect
  to_s
end

#instance_of?(klass) ⇒ Boolean

Returns:



304
305
306
# File 'opal/opal/corelib/kernel.rb', line 304

def instance_of?(klass)
  `self._klass === klass`
end

#instance_variable_defined?(name) ⇒ Boolean

Returns:



308
309
310
# File 'opal/opal/corelib/kernel.rb', line 308

def instance_variable_defined?(name)
  `$opal.hasOwnProperty.call(self, name.substr(1))`
end

#instance_variable_get(name) ⇒ Object



312
313
314
315
316
317
318
# File 'opal/opal/corelib/kernel.rb', line 312

def instance_variable_get(name)
  %x{
    var ivar = self[name.substr(1)];

    return ivar == null ? nil : ivar;
  }
end

#instance_variable_set(name, value) ⇒ Object



320
321
322
# File 'opal/opal/corelib/kernel.rb', line 320

def instance_variable_set(name, value)
  `self[name.substr(1)] = value`
end

#instance_variablesObject



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'opal/opal/corelib/kernel.rb', line 324

def instance_variables
  %x{
    var result = [];

    for (var name in self) {
      if (name.charAt(0) !== '$') {
        if (name !== '_klass' && name !== '_id') {
          result.push('@' + name);
        }
      }
    }

    return result;
  }
end

#Integer(value, base = nil) ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'opal/opal/corelib/kernel.rb', line 340

def Integer(value, base = nil)
  if String === value
    if value.empty?
      raise ArgumentError, "invalid value for Integer: (empty string)"
    end

    return `parseInt(#{value}, #{base || `undefined`})`
  end

  if base
    raise ArgumentError "base is only valid for String values"
  end

  case value
  when Integer
    value

  when Float
    if value.nan? or value.infinite?
      raise FloatDomainError, "unable to coerce #{value} to Integer"
    end

    value.to_int

  when NilClass
    raise TypeError, "can't convert nil into Integer"

  else
    if value.respond_to? :to_int
      value.to_int
    elsif value.respond_to? :to_i
      value.to_i
    else
      raise TypeError, "can't convert #{value.class} into Integer"
    end
  end
end

#is_a?(klass) ⇒ Boolean Also known as: kind_of?

Returns:



388
389
390
# File 'opal/opal/corelib/kernel.rb', line 388

def is_a?(klass)
  `$opal.is_a(self, klass)`
end

#lambda(&block) ⇒ Object



394
395
396
397
398
# File 'opal/opal/corelib/kernel.rb', line 394

def lambda(&block)
  `block.is_lambda = true`

  block
end

#loop(&block) ⇒ Object



400
401
402
403
404
405
406
407
408
409
410
# File 'opal/opal/corelib/kernel.rb', line 400

def loop(&block)
  %x{
    while (true) {
      if (block() === $breaker) {
        return $breaker.$v;
      }
    }
  }

  self
end

#method(name) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'opal/opal/corelib/kernel.rb', line 24

def method(name)
  %x{
    var meth = self['$' + name];

    if (!meth || meth.rb_stub) {
      #{raise NameError, "undefined method `#{name}' for class `#{self.class.name}'"};
    }

    return #{Method.new(self, `meth`, name)};
  }
end

#methods(all = true) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'opal/opal/corelib/kernel.rb', line 36

def methods(all = true)
  %x{
    var methods = [];

    for (var key in self) {
      if (key[0] == "$" && typeof(self[key]) === "function") {
        if (all == false || all === nil) {
          if (!$opal.hasOwnProperty.call(self, key)) {
            continue;
          }
        }
        if (self[key].rb_stub === undefined) {
          methods.push(key.substr(1));
        }
      }
    }

    return methods;
  }
end

#nil?Boolean

Returns:



412
413
414
# File 'opal/opal/corelib/kernel.rb', line 412

def nil?
  false
end

#p(*args) ⇒ Object



443
444
445
446
447
# File 'opal/opal/corelib/kernel.rb', line 443

def p(*args)
  args.each { |obj| $stdout.puts obj.inspect }

  args.length <= 1 ? args[0] : args
end


449
450
451
# File 'opal/opal/corelib/kernel.rb', line 449

def print(*strs)
  $stdout.print(*strs)
end

#printf(*args) ⇒ Object



418
419
420
421
422
423
424
# File 'opal/opal/corelib/kernel.rb', line 418

def printf(*args)
  if args.length > 0
    print format(*args)
  end

  nil
end

#private_methodsObject



426
427
428
# File 'opal/opal/corelib/kernel.rb', line 426

def private_methods
  []
end

#proc(&block) ⇒ Object



430
431
432
433
434
435
436
437
# File 'opal/opal/corelib/kernel.rb', line 430

def proc(&block)
  unless block
    raise ArgumentError, "tried to create Proc object without a block"
  end

  `block.is_lambda = false`
  block
end

#puts(*strs) ⇒ Object



439
440
441
# File 'opal/opal/corelib/kernel.rb', line 439

def puts(*strs)
  $stdout.puts(*strs)
end

#raise(exception = undefined, string = undefined) ⇒ Object Also known as: fail



458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'opal/opal/corelib/kernel.rb', line 458

def raise(exception = undefined, string = undefined)
  %x{
    if (exception == null && #$!) {
      exception = #$!;
    }
    else if (exception._isString) {
      exception = #{RuntimeError.new exception};
    }
    else if (!#{exception.is_a? Exception}) {
      exception = #{exception.new string};
    }

    #{$! = exception};
    throw exception;
  }
end

#rand(max = undefined) ⇒ Object Also known as: srand



477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# File 'opal/opal/corelib/kernel.rb', line 477

def rand(max = undefined)
  %x{
    if (max === undefined) {
      return Math.random();
    }
    else if (max._isRange) {
      var arr = #{max.to_a};

      return arr[#{rand(`arr.length`)}];
    }
    else {
      return Math.floor(Math.random() *
        Math.abs(#{Opal.coerce_to max, Integer, :to_int}));
    }
  }
end

#respond_to?(name, include_all = false) ⇒ Boolean

Returns:



496
497
498
499
500
501
502
503
504
505
506
507
508
# File 'opal/opal/corelib/kernel.rb', line 496

def respond_to?(name, include_all = false)
  return true if respond_to_missing?(name)

  %x{
    var body = self['$' + name];

    if (typeof(body) === "function" && !body.rb_stub) {
      return true;
    }
  }

  false
end

#respond_to_missing?(method_name) ⇒ Boolean

Returns:



590
591
592
# File 'opal/opal/corelib/kernel.rb', line 590

def respond_to_missing?(method_name)
  false
end

#singleton_classObject



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'opal/opal/corelib/kernel.rb', line 513

def singleton_class
  %x{
    if (self._isClass) {
      if (self.__meta__) {
        return self.__meta__;
      }

      var meta = new $opal.Class._alloc;
      meta._klass = $opal.Class;
      self.__meta__ = meta;
      // FIXME - is this right? (probably - methods defined on
      // class' singleton should also go to subclasses?)
      meta._proto = self.constructor.prototype;
      meta._isSingleton = true;
      meta.__inc__ = [];
      meta._methods = [];

      meta._scope = self._scope;

      return meta;
    }

    if (self._isClass) {
      return self._klass;
    }

    if (self.__meta__) {
      return self.__meta__;
    }

    else {
      var orig_class = self._klass,
          class_id   = "#<Class:#<" + orig_class._name + ":" + orig_class._id + ">>";

      var Singleton = function () {};
      var meta = Opal.boot(orig_class, Singleton);
      meta._name = class_id;

      meta._proto = self;
      self.__meta__ = meta;
      meta._klass = orig_class._klass;
      meta._scope = orig_class._scope;
      meta.__parent = orig_class;

      return meta;
    }
  }
end

#String(str) ⇒ Object



564
565
566
# File 'opal/opal/corelib/kernel.rb', line 564

def String(str)
  `String(str)`
end

#tap {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:

  • _self (Kernel)

    the object that the method was called on



568
569
570
571
# File 'opal/opal/corelib/kernel.rb', line 568

def tap(&block)
  yield self
  self
end

#to_procObject



573
574
575
# File 'opal/opal/corelib/kernel.rb', line 573

def to_proc
  self
end

#to_sObject



577
578
579
# File 'opal/opal/corelib/kernel.rb', line 577

def to_s
  `"#<" + #{self.class.name} + ":" + self._id + ">"`
end

#warn(*strs) ⇒ Object



453
454
455
456
# File 'opal/opal/corelib/kernel.rb', line 453

def warn(*strs)
  $stderr.puts(*strs) unless $VERBOSE.nil? || strs.empty?
  nil
end