Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Branch: master
Fetching contributors…

Cannot retrieve contributors at this time

105 lines (74 sloc) 2.53 KB
Bridging the Gap
Andreas Haller, @ahx
Thorben Schröder, @walski
"JavaScript and Ruby at the same time without freaking out about it."
Not going to use "Ruby in JavaScript."
Ruby Bytecode inside Javascript?! Whoa. "Hot Ruby Web Toolkit." Oh. It doesn't work.
JavaScript in Ruby using Google's V8.
require 'v8'
cxt =
cxt.eval('7 * 6') #=> 42
Runs in a sandbox, "safe by default," only have access to JavaScript objects, not I/O, filesystem. Use case: execute client code that might not be safe; query language
Pass Ruby in:
class MyMath
def plus(a, b)
a + b
cxt['math'] =
cxt.eval(", 22)") #=> 42
Simple example
var Helpers = {
foo: function(a,b) { return a * b }
obj = cxt.load('helpers.js')
obj[:Helpers].class # => V8::Object
obj[:Helpers].foo(3, 4) => 12
* The JavaScript Way
CommonJS (
CommonJS Modules (
But you have to deal with browser crap. This is not for the browser. Same-origin policies, etc. So use to package up dependencies and bundle everything up for the browser. Or Rack::Modulr is a Rack middleware.
The exciting part: IncludeJS is their thing.
// addition.js = function(a, b) {
return a + b;
// calculator.rb
adder = IncludeJS.require('addition'), 2) # => 3
* The Ruby Way
module Addition
def plus(a, b)
a + b
class Calculator
include Addition
* So how do we do this in JS?
// calculator.rb
class Calculator
include IncludeJS.module('addition') # here is the magic
calculator =, 3) # => 5
* But what about JS?
Ideally should be the same behavior on the JS side. So:
// addition.js = function(a, b) {
return a + b;
var Calculator = {}
$.extend(Calculator, require ('addition'))
* The whole point here is that you're using the same code (addition) in both JS and in Ruby. Write re-usable modules in JS. JS approach: write CommonJS modules, use them in Ruby with Include JS (too fast to copy down)
Ruby Approach:
write CommonJS modules
use them as modules in Ruby with IncludeJS
use them as object extensions in JS with jQuery
Jump to Line
Something went wrong with that request. Please try again.