Ruby2js
Minimal yet extensible Ruby to JavaScript conversion.
Description
The base package maps Ruby syntax to JavaScript semantics. For example,
a Ruby Hash literal becomes a JavaScript Object literal. Ruby symbols
become JavaScript strings. Ruby method calls become JavaScript function
calls IF there are either one or more arguments passed OR parenthesis are
used, otherwise Ruby method calls become JavaScript property accesses.
By default, methods, lambdas, and procs return undefined.
Ruby attribute accessors, methods defined with no parameters and no parenthesis, as well as setter method definitions, are mapped to Object.defineProperty, so avoid these if you wish to target users running IE8 or lower.
Filters may be provided to add Ruby-specific or framework specific behavior. Filters are essentially macro facilities that operate on an AST representation of the code.
See notimplemented_spec for a list of Ruby features known to be not implemented.
Synopsis
Basic:
require 'ruby2js'
puts Ruby2JS.convert("a={age:3}\na.age+=1")
With filter:
require 'ruby2js/filter/functions'
puts Ruby2JS.convert('"2A".to_i(16)')
Conversions can be explored interactively using the demo provided.
Introduction
JavaScript is a language where 0 is considered false, strings are
immutable, and the behaviors for operators like == are, at best,
convoluted.
Any attempt to bridge the semantics of Ruby and JavaScript will involve trade-offs. Consider the following expression:
a[-1]
Programmers who are familiar with Ruby will recognize that this returns the
last element (or character) of an array (or string). However, the meaning is
quite different if a is a Hash.
One way to resolve this is to change the way indexing operators are evaluated, and to provide a runtime library that adds properties to global JavaScript objects to handle this. This is the approach that Opal takes. It is a fine approach, with a number of benefits. It also has some notable drawbacks. For example, readability and compatibility with other frameworks.
Another approach is to simply accept JavaScript semantics for what they are.
This would mean that negative indexes would return undefined for arrays
and strings. This is the base approach provided by ruby2js.
A third approach would be to do static transformations on the source in order
to address common usage patterns or idioms. These transformations can even be
occasionally unsafe, as long as the transformations themselves are opt-in.
ruby2js provides a number of such filters, including one that handles negative
indexes when passed as a literal. As indicated above, this is unsafe in that
it will do the wrong thing when it encounters a hash index which is expressed
as a literal constant negative one. My experience is that such is rare enough
to be safely ignored, but YMMV. More troublesome, this also won’t work when
the index is not a literal (e.g., a[n]) and the index happens to be
negative at runtime.
This quickly gets into gray areas. each in Ruby is a common method that
facilitates iteration over arrays. forEach is the JavaScript equivalent.
Mapping this is fine until you start using a framework like jQuery which
provides a function named each.
Fortunately, Ruby provides ? and ! as legal suffixes for method names,
Ruby2js filters do an exact match, so if you select a filter that maps each
to forEach, each! will pass through the filter. The final code that emits
JavaScript function calls and parameter accesses will strip off these
suffixes.
Static transformations and runtime libraries aren't aren’t mutually exclusive.
With enough of each, one could reproduce any functionality desired. Just be
forewarned, that implementing a function like method_missing would require a
lot of work.
Integrations
While this is a low level library suitable for DIY integration, one of the obvious uses of a tool that produces JavaScript is by web servers. Ruby2JS includes three such integrations:
As you might expect, CGI is a bit sluggish. By constrast, Sinatra and Rails are quite speedy as the bulk of the time is spend on the initial load of the required libraries.
Filters
In general, making use of a filter is as simple as requiring it. If multiple filters are selected, they will all be applied in parallel in one pass through the script.
strict adds
'use strict';to the outputreturn adds
returnto the last expression in functions-
.all?becomes.every.any?becomes.some.chrbecomesfromCharCode.clearbecomes.length = 0.deletebecomesdelete target[arg].downcasebecomes.toLowerCase.eachbecomesforEach.each_with_indexbecomes.forEach.end_with?becomes.slice(-arg.length) == arg.empty?becomes.length == 0.firstbecomes[0].first(n)becomes.slice(0, n).gsubbecomesreplace //g.include?becomes.indexOf() != -1.keysbecomesObject.keys().lastbecomes[*.length-1].last(n)becomes.slice(*.length-1, *.length).maxbecomesMath.max.apply(Math).minbecomesMath.min.apply(Math).ordbecomescharCodeAt(0)putsbecomesconsole.log.replacebecomes.length = 0; ...push.apply(*).start_with?becomes.substring(0, arg.length) == arg.subbecomes.replace.to_abecomesto_Array.to_fbecomesparseFloat.to_ibecomesparseInt.to_sbecomes.to_String.upcasebecomes.toUpperCase[-n]becomes[*.length-n]for literal values ofn[n...m]becomes.slice(n,m)[n..m]becomes.slice(n,m+1)[/r/, n]becomes.match(/r/)[n].sub!and.gsub!become equivalentx = x.replacestatements.map!,.reverse!, and.selectbecome equivalent.splice(0, .length, *.method())statementssetIntervalandsetTimeoutallow block to be treated as the first parameter on the call- for the following methods, if the block consists entirely of a simple
expression (or ends with one), a
returnis added prior to the expression:sub,gsub,any?,all?,map.
-
.clone()becomes_.clone().compact()becomes_.compact().count_by {}becomes_.countBy {}.find {}becomes_.find {}.find_by()becomes_.findWhere().flatten()becomes_.flatten().group_by {}becomes_.groupBy {}.has_key?()becomes_.has().index_by {}becomes_.indexBy {}.invert()becomes_.invert().invoke(&:n)becomes_.invoke(, :n).map(&:n)becomes_.pluck(, :n).merge!()becomes_.extend().merge()becomes_.extend({}, ).reduce {}becomes_.reduce {}.reduce()becomes_.reduce().reject {}becomes_.reject {}.sample()becomes_.sample().select {}becomes_.select {}.shuffle()becomes_.shuffle().size()becomes_.size().sort()becomes_.sort_by(, _.identity).sort_by {}becomes_.sortBy {}.times {}becomes_.times {}.values()becomes_.values().where()becomes_.where().zip()becomes_.zip()(n...m)becomes_.range(n, m)(n..m)becomes_.range(n, m+1).compact!,.flatten!,shuffle!,reject!,sort_by!, and.uniqbecome equivalent.splice(0, .length, *.method())statements- for the following methods, if the block consists entirely of a simple
expression (or ends with one), a
returnis added prior to the expression:reduce,sort_by,group_by,index_by,count_by,find,select,reject.
-
- maps Ruby unary operator
~to jQuery$function - maps Ruby attribute syntax to jquery attribute syntax
- maps
$$to jQuery$function - defaults the fourth parameter of $$.post to :jquery, allowing Ruby block syntax to be used for the success function.
- maps Ruby unary operator
-
- maps Ruby
moduletoangular.module - maps
filter,controller,factory, anddirectiveto calls to angular module functions. - maps
usestatements to formal arguments or array values (as appropriate) depending on the module function. - maps
watchstatments to calls to$scope.$watch. - tracks globals variable and constant references and adds additional
implicit
usestatements - maps constant assignments in an angular module to a filter
- maps class definitions in an angular module to a filter
- within a controller or within a
linkmethod in a directive:- maps
apply,broadcast,digest,emit,eval,evalAsync, andparentcalls to$scopefunctions. - maps
apply!,broadcast!,digest!,eval!, andevalAsync!calls to$rootScopefunctions. - maps
filtercalls to '$filter` calls. - maps
timeoutandintervalcalls with a block to$timeoutand$intervalcalls where the block is passed as the first parameter.
- maps
- maps Ruby
-
- maps
casestatements on$routeProviderto angular.js module configuration. - adds implicit module
useofngRoutewhen such acasestatement is encountered
- maps
-
- maps
$resource.newstatements on$resourcefunction calls. - adds implicit module
useofngResourcewhen$resource.newcalls are encountered
- maps
Wunderbar includes additional demos:
angularjs makes use of the angular filters to implement the angular.js tutorial. This demo includes:
Picking a Ruby to JS mapping tool
dsl — A domain specific language, where code is written in one language and errors are given in another. -- Devil’s Dictionary of Programming
If you simply want to get a job done, and would like a mature and tested framework, and only use one of the many integrations that Opal provides, then Opal is the way to go right now.
ruby2js is for those that want to produce JavaScript that looks like it wasn’t machine generated, and want the absolute bare minimum in terms of limitations as to what JavaScript can be produced.
And, of course, the right solution might be to use CoffeeScript instead.
License
(The MIT License)
Copyright (c) 2009, 2013 Macario Ortega, Sam Ruby
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.