Skip to content

Instantly share code, notes, and snippets.

@adambeynon
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adambeynon/8765983 to your computer and use it in GitHub Desktop.
Save adambeynon/8765983 to your computer and use it in GitHub Desktop.
Notes/summary from weekend discussion (Jan, 31).

Notes/summary from weekend discussion (Jan, 31).

Variables: nil, true, false, self

nil == null == undefined

nil   # => null
true  # => true
false # => false
self  # => this

Array, String, Numeric, Proc, Boolean

All compile to their native counterparts. Again, we capture certain method calls to handle them the ruby way. Compiler macro magic?

$global variables

Compile as they are.

$document
$VERBOSE = true
document
window.VERBOSE = true

method calls

object.foo 1, 2, 3

do_something 4, 5, 6
object.foo(1, 2, 3)
this.do_something(4, 5, 6)

get

Support js properties and method calls:

object.foo
__get__(object, 'foo')

function __get__(obj, property) {
  var value;
  if (typeof(value = obj[property]) === 'function') {
    return value.call(obj);
  }
  
  return value;
}

set

object.foo = 100
__set__(object, 'foo', 100)

function __set__(obj, property, value) {
  var func = obj['set' + property];
  
  if (typeof(func) === 'function') {
    return func.call(obj, value);
  }
  
  return obj[property] = value;
}

[] aref

object[foo]
__aref__(object, foo)

function __aref__(object, ref) {
  var func = object.__aref__;
  
  if (func) {
    return func.call(object, ref);
  }
  
  return object[ref];
}

[]= aset

object[foo] = 100

function __aset__(object, ref, value) {
  var func = object.__aset__;
  
  if (func) {
    return func.call(object, ref, value);
  }
  
  return object[ref] = value;
}

Special methods

We capture methods that might clash with native methods. E.g., we capture #each and handle it.

All methods in array and hash:

[1, 2, 3].each { |a| a }
{:a => 10}.each { |b| b }
__each__([1, 2, 3], function(a) { return a; })
__each__({"a": 10}, function(b) { return b; })

function __each__(object, block) {
  if (object.__each__) {
    return object.__each__(block);
  }
  else if (object.isArray) {
    for (var i = 0; i < object.length; i++) {
      block(object);
    }
  }
  else {
    for (var key in obj) {
      block(key);
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment