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



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

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



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

def caller
  []
end

#classObject



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

def class
  `self._klass`
end

#cloneObject



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

def clone
  copy = self.class.allocate

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

  copy
end

#copy_instance_variables(other) ⇒ Object



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

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



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

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

#equal?(other) ⇒ Boolean

Returns:



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

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

#extend(*mods) ⇒ Object



148
149
150
151
152
153
154
155
156
# File 'opal/opal/corelib/kernel.rb', line 148

def extend(*mods)
  %x{
    for (var i = 0, length = mods.length; i < length; i++) {
      #{ self.singleton_class.include `mods[i]` };
    }

    return self;
  }
end

#Float(value) ⇒ Object



372
373
374
375
376
377
378
379
380
# File 'opal/opal/corelib/kernel.rb', line 372

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



158
159
160
161
162
163
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
# File 'opal/opal/corelib/kernel.rb', line 158

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



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

def freeze
  @___frozen___ = true
  self
end

#frozen?Boolean

Returns:



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

def frozen?
  @___frozen___ || false
end

#hashObject



287
288
289
# File 'opal/opal/corelib/kernel.rb', line 287

def hash
  `self._id`
end

#initialize_copy(other) ⇒ Object



291
292
# File 'opal/opal/corelib/kernel.rb', line 291

def initialize_copy(other)
end

#inspectObject



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

def inspect
  to_s
end

#instance_of?(klass) ⇒ Boolean

Returns:



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

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

#instance_variable_defined?(name) ⇒ Boolean

Returns:



302
303
304
# File 'opal/opal/corelib/kernel.rb', line 302

def instance_variable_defined?(name)
  `self.hasOwnProperty(name.substr(1))`
end

#instance_variable_get(name) ⇒ Object



306
307
308
309
310
311
312
# File 'opal/opal/corelib/kernel.rb', line 306

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

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

#instance_variable_set(name, value) ⇒ Object



314
315
316
# File 'opal/opal/corelib/kernel.rb', line 314

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

#instance_variablesObject



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'opal/opal/corelib/kernel.rb', line 318

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



334
335
336
337
338
339
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
# File 'opal/opal/corelib/kernel.rb', line 334

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:



382
383
384
# File 'opal/opal/corelib/kernel.rb', line 382

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

#lambda(&block) ⇒ Object



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

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

  block
end

#loop(&block) ⇒ Object



394
395
396
397
398
399
400
401
402
403
404
# File 'opal/opal/corelib/kernel.rb', line 394

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
# 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;
          }
        }

        methods.push(key.substr(1));
      }
    }

    return methods;
  }
end

#nil?Boolean

Returns:



406
407
408
# File 'opal/opal/corelib/kernel.rb', line 406

def nil?
  false
end

#p(*args) ⇒ Object



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

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

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

#printf(*args) ⇒ Object



412
413
414
415
416
417
418
# File 'opal/opal/corelib/kernel.rb', line 412

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

  nil
end

#private_methodsObject



420
421
422
# File 'opal/opal/corelib/kernel.rb', line 420

def private_methods
  []
end

#proc(&block) ⇒ Object



424
425
426
427
428
429
430
431
# File 'opal/opal/corelib/kernel.rb', line 424

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 Also known as: print



433
434
435
# File 'opal/opal/corelib/kernel.rb', line 433

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

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



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'opal/opal/corelib/kernel.rb', line 450

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};
    }

    throw exception;
  }
end

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



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'opal/opal/corelib/kernel.rb', line 468

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:



487
488
489
490
491
492
# File 'opal/opal/corelib/kernel.rb', line 487

def respond_to?(name, include_all = false)
  %x{
    var body = self['$' + name];
    return (!!body) && !body.rb_stub;
  }
end

#respond_to_missing?(method_name) ⇒ Boolean

Returns:



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

def respond_to_missing? method_name
  false
end

#singleton_classObject



497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
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
# File 'opal/opal/corelib/kernel.rb', line 497

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



548
549
550
# File 'opal/opal/corelib/kernel.rb', line 548

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

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

Yields:

  • (_self)

Yield Parameters:

  • _self (Kernel)

    the object that the method was called on



552
553
554
555
# File 'opal/opal/corelib/kernel.rb', line 552

def tap(&block)
  yield self
  self
end

#to_procObject



557
558
559
# File 'opal/opal/corelib/kernel.rb', line 557

def to_proc
  self
end

#to_sObject



561
562
563
# File 'opal/opal/corelib/kernel.rb', line 561

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

#warn(*strs) ⇒ Object



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

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