- Notifications
You must be signed in to change notification settings - Fork37
Ruby to JavaScript conversion
License
ruby2js/ruby2js
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Minimal yet extensible Ruby to JavaScript conversion.
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 IFthere are either one or more arguments passed ORparenthesis are used
- otherwise Ruby method calls become JavaScript property accesses.
- by default, methods and procs return
undefined - splats mapped to spread syntax when ES2015 or later is selected, andto equivalents using
apply,concat,slice, andargumentsotherwise. - ruby string interpolation is expanded into string + operations
andandorbecome&&and||a ** bbecomesMath.pow(a,b)<< abecomes.push(a)unlessbecomesif !untilbecomeswhile !caseandwhenbecomesswitchandcase- ruby for loops become js for loops
(1...4).step(2){becomesfor (var i = 1; i < 4; i += 2) {x.forEach { next }becomesx.forEach(function() {return})lambda {}andproc {}becomesfunction() {}class Person; endbecomesfunction Person() {}- instance methods become prototype methods
- instance variables become underscored,
@namebecomesthis._name - self is assigned to this is if used
- Any block becomes and explicit argument
new Promise do; y(); endbecomesnew Promise(function() {y()}) - regular expressions are mapped to js
raisebecomesthrow- expressions enclosed in backtick operators (``) and
%x{}literals areevaluated in the context of the caller and the results are insertedinto the generated JavaScript.
Ruby attribute accessors, methods defined with no parameters and noparenthesis, as well as setter method definitions, aremapped toObject.defineProperty,so avoid these if you wish to target users running IE8 or lower.
While both Ruby and JavaScript have open classes, Ruby unifies the syntax fordefining and extending an existing class, whereas JavaScript does not. Thismeans that Ruby2JS needs to be told when a class is being extended, which isdone by prepending theclass keyword with two plus signs, thus:++class C; ...; end.
Filters may be provided to add Ruby-specific or framework specificbehavior. Filters are essentially macro facilities that operate onan AST representation of the code.
Seenotimplemented_specfor a list of Ruby featuresknown to be not implemented.
Basic:
require'ruby2js'putsRuby2JS.convert("a={age:3}\na.age+=1")
With filter:
require'ruby2js/filter/functions'putsRuby2JS.convert('"2A".to_i(16)')
Enable ES2015 support:
putsRuby2JS.convert('"#{a}"',eslevel:2015)
Enable strict support:
putsRuby2JS.convert('a=1',strict:true)
Emit strict equality comparisons:
putsRuby2JS.convert('a==1',comparison::identity)
Emit nullish coalescing operators:
putsRuby2JS.convert('a || 1',or::nullish)
WithExecJS:
require'ruby2js/execjs'require'date'context=Ruby2JS.compile(Date.today.strftime('d = new Date(%Y, %-m-1, %-d)'))putscontext.eval('d.getYear()')+1900
Conversions can be explored interactively using thedemo provided.
JavaScript is a language where0 is consideredfalse, strings areimmutable, and the behaviors for operators like== are, at best,convoluted.
Any attempt to bridge the semantics of Ruby and JavaScript will involvetrade-offs. Consider the following expression:
a[-1]
Programmers who are familiar with Ruby will recognize that this returns thelast element (or character) of an array (or string). However, the meaning isquite different ifa 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 JavaScriptobjects to handle this. This is the approach thatOpaltakes. It is a fine approach, with a number of benefits. It also has somenotable drawbacks. For example,readabilityandcompatibility with other frameworks.
Another approach is to simply accept JavaScript semantics for what they are.This would mean that negative indexes would returnundefined for arraysand strings. This is the base approach provided by ruby2js.
A third approach would be to do static transformations on the source in orderto address common usage patterns or idioms. These transformations can even beoccasionally unsafe, as long as the transformations themselves are opt-in.ruby2js provides a number of such filters, including one that handles negativeindexes when passed as a literal. As indicated above, this is unsafe in thatit will do the wrong thing when it encounters a hash index which is expressedas a literal constant negative one. My experience is that such is rare enoughto be safely ignored, but YMMV. More troublesome, this also won’t work whenthe index is not a literal (e.g.,a[n]) and the index happens to benegative at runtime.
This quickly gets into gray areas.each in Ruby is a common method thatfacilitates iteration over arrays.forEach is the JavaScript equivalent.Mapping this is fine until you start using a framework like jQuery whichprovides a function namedeach.
Fortunately, Ruby provides? and! as legal suffixes for method names,Ruby2js filters do an exact match, so if you select a filter that mapseachtoforEach,each! will pass through the filter. The final code that emitsJavaScript function calls and parameter accesses will strip off thesesuffixes.
This approach works well if it is an occasional change, but if the usage ispervasive, most filters support options toexclude a list of mappings,for example:
putsRuby2JS.convert('jQuery("li").each {|index| ...}',exclude::each)
Alternatively, you can change the default:
Ruby2JS::Filter.exclude:each
Static transformations and runtime libraries aren't aren’t mutually exclusive.With enough of each, one could reproduce any functionality desired. Just beforewarned, that implementing a function likemethod_missing would require alot of work.
While this is a low level library suitable for DIY integration, one of theobvious uses of a tool that produces JavaScript is by web servers. Ruby2JSincludes three such integrations:
As you might expect, CGI is a bit sluggish. By contrast, Sinatra and Railsare quite speedy as the bulk of the time is spent on the initial load of therequired libraries.
In general, making use of a filter is as simple as requiring it. If multiplefilters are selected, they will all be applied in parallel in one pass throughthe script.
returnadds
returnto the last expression in functions.requiresupports
requireandrequire_relativestatements. Contents of filesthat are required are converted to JavaScript and expanded inline.requirefunction calls in expressions are left alone.camelCaseconverts
underscore_casetocamelCase. This filter should be required afterall other filters have been required. Seecamelcase_specfor examples of conversion results..all?becomes.every.any?becomes.some.chrbecomesfromCharCode.clearbecomes.length = 0.deletebecomesdelete target[arg].downcasebecomes.toLowerCase.eachbecomes.forEach.each_keybecomesfor (i in ...) {}.each_pairbecomesfor (var key in item) {var value = item[key]; ...}.each_valuebecomes.forEach.each_with_indexbecomes.forEach.end_with?becomes.slice(-arg.length) == arg.empty?becomes.length == 0.find_indexbecomesfindIndex.firstbecomes[0].first(n)becomes.slice(0, n).gsubbecomesreplace(//g).include?becomes.indexOf() != -1.inspectbecomesJSON.stringify().keys()becomesObject.keys().lastbecomes[*.length-1].last(n)becomes.slice(*.length-1, *.length).lstripbecomes.replace(/^\s+/, "").maxbecomesMath.max.apply(Math).mergebecomesObject.assign({}, ...).merge!becomesObject.assign().minbecomesMath.min.apply(Math).nil?becomes== null.ordbecomescharCodeAt(0)putsbecomesconsole.log.replacebecomes.length = 0; ...push.apply(*).respond_to?becomesright in left.rstripbecomes.replace(/s+$/, "").scanbecomes.match(//g).start_with?becomes.substring(0, arg.length) == arg.upto(lim)becomesfor (var i=num; i<=lim; i+=1).downto(lim)becomesfor (var i=num; i>=lim; i-=1).step(lim, n).eachbecomesfor (var i=num; i<=lim; i+=n).step(lim, -n).eachbecomesfor (var i=num; i>=lim; i-=n)(0..a).to_abecomesArray.apply(null, {length: a}).map(Function.call, Number)(b..a).to_abecomesArray.apply(null, {length: (a-b+1)}).map(Function.call, Number).map(function (idx) { return idx+b })(b...a).to_abecomesArray.apply(null, {length: (a-b)}).map(Function.call, Number).map(function (idx) { return idx+b }).stripbecomes.trim.subbecomes.replace.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][/r/, n]=becomes.replace(/r/, ...)(1..2).each {|i| ...}becomesfor (var i=1 i<=2; i+=1)"string" * lengthbecomesnew Array(length + 1).join("string").sub!and.gsub!become equivalentx = x.replacestatements.map!,.reverse!, and.selectbecome equivalent.splice(0, .length, *.method())statements@foo.call(args)becomesthis._foo(args)@@foo.call(args)becomesthis.constructor._foo(args)Array(x)becomesArray.prototype.slice.call(x)delete xbecomesdelete x(note lack of parenthesis)setIntervalandsetTimeoutallow block to be treated as thefirst parameter on the call- for the following methods, if the block consists entirely of a simpleexpression (or ends with one), a
returnis added prior to theexpression:sub,gsub,any?,all?,map,find,find_index. - New classes subclassed off of
Exceptionwill become subclassed offofErrorinstead; and default constructors will be provided loop do...endwill be replaced withwhile (true) {...}raise Exception.new(...)will be replaced withthrow new Error(...)
Additionally, there is one mapping that will only be done if explicitlyincluded (pass
include: :classas aconvertoption to enable):.classbecomes.constructor
Allows you to turn certain method calls with a string argument into taggedtemplate literals. By default it supports html and css, so you can write
html "<div>#{1+2}</div>"which converts tohtml`<div>${1+2}</div>`.Works nicely with squiggly heredocs for multi-line templates as well. If youneed to configure the tag names yourself, pass atemplate_literal_tagsoption toconvertwith an array of tag name symbols.Note: these conversions are only done if eslevel >= 2015
Provides conversion of import and export statements for use with modern ES builders like Webpack.
Examples:
import
import"./index.scss"# => import "./index.scss"importSomethingfrom"./lib/something"# => import Something from "./lib/something"importSomething,"./lib/something"# => import Something from "./lib/something"import[LitElement,html,css],from:"lit-element"# => import { LitElement, html, css } from "lit-element"importReact,from:"react"# => import React from "react"importReact,as:"*",from:"react"# => import React as * from "react"
export
exporthash={ab:123}# => export const hash = {ab: 123};exportfunc=->(x){x *10}# => export const func = x => x * 10;exportdefmultiply(x,y)returnx *yend# => export function multiply(x, y) {# return x * y# }exportdefaultclassMyClassend# => export default class MyClass {# };# or final export statement:export[one,two,default:three]# => export { one, two, three as default }
`command`becomeschild_process.execSync("command", {encoding: "utf8"})ARGVbecomesprocess.argv.slice(2)__dir__becomes__dirnameDir.chdirbecomesprocess.chdirDir.entriesbecomesfs.readdirSyncDir.mkdirbecomesfs.mkdirSyncDir.mktmpdirbecomesfs.mkdtempSyncDir.pwdbecomesprocess.cwdDir.rmdirbecomesfs.rmdirSyncENVbecomesprocess.env__FILE__becomes__filenameFile.chmodbecomesfs.chmodSyncFile.chownbecomesfs.chownSyncFile.cpbecomesfs.copyFileSyncFile.exist?becomesfs.existsSyncFile.lchmodbecomesfs.lchmodSyncFile.linkbecomesfs.linkSyncFile.lnbecomesfs.linkSyncFile.lstatbecomesfs.lstatSyncFile.readbecomesfs.readFileSyncFile.readlinkbecomesfs.readlinkSyncFile.realpathbecomesfs.realpathSyncFile.renamebecomesfs.renameSyncFile.statbecomesfs.statSyncFile.symlinkbecomesfs.symlinkSyncFile.truncatebecomesfs.truncateSyncFile.unlinkbecomesfs.unlinkSyncFileUtils.cdbecomesprocess.chdirFileUtils.cpbecomesfs.copyFileSyncFileUtils.lnbecomesfs.linkSyncFileUtils.ln_sbecomesfs.symlinkSyncFileUtils.mkdirbecomesfs.mkdirSyncFileUtils.mvbecomesfs.renameSyncFileUtils.pwdbecomesprocess.cwdFileUtils.rmbecomesfs.unlinkSyncIO.readbecomesfs.readFileSyncIO.writebecomesfs.writeFileSyncsystembecomeschild_process.execSync(..., {stdio: "inherit"})
add_childbecomesappendChildadd_next_siblingbecomesnode.parentNode.insertBefore(sibling, node.nextSibling)add_previous_siblingbecomesnode.parentNode.insertBefore(sibling, node)afterbecomesnode.parentNode.insertBefore(sibling, node.nextSibling)atbecomesquerySelectorattrbecomesgetAttributeattributebecomesgetAttributeNodebeforebecomesnode.parentNode.insertBefore(sibling, node)cdata?becomesnode.nodeType === Node.CDATA_SECTION_NODEchildrenbecomeschildNodescomment?becomesnode.nodeType === Node.COMMENT_NODEcontentbecomestextContentcreate_elementbecomescreateElementdocumentbecomesownerDocumentelement?becomesnode.nodeType === Node.ELEMENT_NODEfragment?becomesnode.nodeType === Node.FRAGMENT_NODEget_attributebecomesgetAttributehas_attributebecomeshasAttributeinner_htmlbecomesinnerHTMLkey?becomeshasAttributenamebecomesnextSiblingnextbecomesnodeNamenext=becomesnode.parentNode.insertBefore(sibling,node.nextSibling)next_elementbecomesnextElementnext_siblingbecomesnextSiblingNokogiri::HTML5becomesnew JSDOM().window.documentNokogiri::HTML5.parsebecomesnew JSDOM().window.documentNokogiri::HTMLbecomesnew JSDOM().window.documentNokogiri::HTML.parsebecomesnew JSDOM().window.documentNokogiri::XML::Node.newbecomesdocument.createElement()parentbecomesparentNodeprevious=becomesnode.parentNode.insertBefore(sibling, node)previous_elementbecomespreviousElementprevious_siblingbecomespreviousSiblingprocessing_instruction?becomesnode.nodeType === Node.PROCESSING_INSTRUCTION_NODEremove_attributebecomesremoveAttributerootbecomesdocumentElementsearchbecomesquerySelectorAllset_attributebecomessetAttributetext?becomesnode.nodeType === Node.TEXT_NODEtextbecomestextContentto_htmlbecomesouterHTML
.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 simpleexpression (or ends with one), a
returnis added prior to theexpression:reduce,sort_by,group_by,index_by,count_by,find,select,reject. is_a?andkind_of?map toObject.prototype.toString.call() === "[object #{type}]" for the following types:Arguments,Boolean,Date,Error,Function,Number,Object,RegExp,String; and maps Ruby names to JavaScript equivalents forException,Float,Hash,Proc, andRegexp. Additionally,is_a?andkind_of?map toArray.isArray()forArray`.
- maps Ruby unary operator
~to jQuery$function - maps Ruby attribute syntax to jquery attribute syntax
.to_abecomestoArray- maps
$$to jQuery$function - defaults the fourth parameter of $$.post to
"json", allowing Ruby blocksyntax to be used for the success function.
- maps Ruby unary operator
- maps subclasses of
Minitest::Testtodescribecalls - maps
test_methods inside subclasses ofMinitest::Testtoitcalls - maps
setup,teardown,before, andaftercalls tobeforeEachandafterEachcalls - maps
assertandrefutecalls toexpect...toBeTruthy()andtoBeFalsycalls - maps
assert_equal,refute_equal,.must_equaland.cant_equalcalls toexpect...toBe()calls - maps
assert_in_delta,refute_in_delta,.must_be_within_delta,.must_be_close_to,.cant_be_within_delta, and.cant_be_close_tocalls toexpect...toBeCloseTo()calls - maps
assert_includes,refute_includes,.must_include, and.cant_includecalls toexpect...toContain()calls - maps
assert_match,refute_match,.must_match, and.cant_matchcalls toexpect...toMatch()calls - maps
assert_nil,refute_nil,.must_be_nil, and.cant_be_nillcallstoexpect...toBeNull()calls - maps
assert_operator,refute_operator,.must_be, and.cant_becalls toexpect...toBeGreaterThan()ortoBeLessThancalls
- maps subclasses of
- maps
export def ftoexports.f = - maps
export async def ftoexports.f = async - maps
export v =toexports.v = - maps
export default proctomodule.exports = - maps
export default async proctomodule.exports = async - maps
export defaulttomodule.exports =
- maps
For ES level < 2020:
- maps
str.matchAll(pattern).forEach {}towhile (match = pattern.exec(str)) {}
Note
patternmust be a simple variable with a value of a regularexpression with thegflag set at runtime.- maps
Wunderbar includes additional demos:
When optioneslevel: 2015 is provided, the following additionalconversions are made:
"#{a}"becomes`${a}`a = 1becomeslet a = 1A = 1becomesconst A = 1a, b = b, abecomes[a, b] = [b, a]a, (foo, *bar) = xbecomeslet [a, [foo, ...bar]] = xdef f(a, (foo, *bar))becomesfunction f(a, [foo, ...bar])def a(b=1)becomesfunction a(b=1)def a(*b)becomesfunction a(...b).each_valuebecomesfor (i of ...) {}a(*b)becomesa(...b)"#{a}"becomes`${a}`lambda {|x| x}becomes(x) => {return x}proc {|x| x}becomes(x) => {x}a {|x|}becomesa((x) => {})class Person; endbecomesclass Person {}(0...a).to_abecomes[...Array(a).keys()](0..a).to_abecomes[...Array(a+1).keys()](b..a).to_abecomesArray.from({length: (a-b+1)}, (_, idx) => idx+b)
ES2015 class support includes constructors, super, methods, class methods,instance methods, instance variables, class variables, getters, setters,attr_accessor, attr_reader, attr_writer, etc.
Additionally, thefunctions filter will provide the following conversion:
Array(x)becomesArray.from(x).inject(n) {}becomes.reduce(() => {}, n)
Finally, keyword arguments and optional keyword arguments will be mapped toparameter detructuring.
When optioneslevel: 2016 is provided, the following additionalconversion is made:
a ** bbecomesa ** b.include?becomes.includes
When optioneslevel: 2017 is provided, the following additionalconversions are made by thefunctions filter:
.values()becomesObject.values().entries()becomesObject.entries().each_pair {}becomes `for (let [key, value] of Object.entries()) {}'
When optioneslevel: 2018 is provided, the following additionalconversion is made by thefunctions filter:
.mergebecomes{...a, ...b}
Additionally, rest arguments can now be used with keyword arguments andoptional keyword arguments.
When optioneslevel: 2019 is provided, the following additionalconversion is made by thefunctions filter:
.flattenbecomes.flat(Infinity).lstripbecomes `.trimEnd.rstripbecomes `.trimStarta.to_hbecomesObject.fromEntries(a)Hash[a]becomesObject.fromEntries(a)
Additionally,rescue without a variable will map tocatch without avariable.
When optioneslevel: 2020 is provided, the following additionalconversions are made:
@xbecomesthis.#x@@xbecomesClassName.#xa&.bbecomesa?.b.scanbecomesArray.from(str.matchAll(/.../g), s => s.slice(1))
When optioneslevel: 2021 is provided, the following additionalconversions are made:
x ||= 1becomesx ||= 1x &&= 1becomesx &&= 1
dsl — A domain specific language, where code is written in one language anderrors are given in another.--Devil’s Dictionary of Programming
If you simply want to get a job done, and would like a mature and testedframework, and only use one of the many integrations thatOpal provides, then Opal is the way to go right now.
ruby2js is for those that want to produce JavaScript that looks like itwasn’t machine generated, and want the absolute bare minimum in terms oflimitations as to what JavaScript can be produced.
And, of course, the right solution might be to useCoffeeScript instead.
(The MIT License)
Copyright (c) 2009, 2013 Macario Ortega, Sam Ruby
Permission is hereby granted, free of charge, to any person obtaininga copy of this software and associated documentation files (the'Software'), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions:
The above copyright notice and this permission notice shall beincluded 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 OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANYCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THESOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
About
Ruby to JavaScript conversion
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors15
Uh oh!
There was an error while loading.Please reload this page.