Opal 1.2

After about 11 years of development we are proud to announce the Opal 1.2 release!

Opal is a Ruby to JavaScript compiler, Ruby runtime and an idiomatic Ruby API for interfacing Browser/Node/anything that uses JS.

Notable new features

Full Ruby 3.0 support! (almost)

We missed a blog post about Opal 1.1, which was released with a preliminary support for Ruby 3.0 features, but Opal 1.2 finalizes this support. Let me update you about them!

An interesting thing is that you can still run older versions of Ruby on the backend, but use the new Ruby 3.0 features when writing Opal code for your frontend.

End-less method definition (Opal 1.1)

No more writing code like this:

def ten
  10
end

Write it in one line!

def ten = 10

Beginless and endless ranges (Opal 1.2)

While those were introduced in earlier Ruby versions (2.6, 2.7), we didn't have those, and now we do! You can absolutely call a[1..] instead of a[1..-1] now!

Numblocks (Opal 1.1)

Also a Ruby 2.7 feature. Personally, I don't like this syntax. Nevertheless, you can use it in Opal now!

[1,2,3].map { _1 ** 2 }

Argument forwarding support def a(...); b(...); end (Opal 1.1)

We support 3.0 level of argument forwarding. No more writing code like

def example(arg1, arg2, *args, **kwargs, &block)
  @arg1, @arg2 = arg1, arg2
  Klass.new(:begin, *args, **kwargs, &block)
end

...when you can write it like this:

def example(arg1, arg2, ...)
  @arg1, @arg2 = arg1, arg2
  Klass.new(:begin, ...)
end

Pattern matching (Opal 1.2)

We support 3.0 level of pattern matching. All kinds of patterns have been fully implemented, including the find pattern.

Pattern matching is optional, if you want to use it, you will need to add require "corelib/pattern_matching" to your application.

Do note, that the find pattern ([1, 2, 3, "needle", 4] => [*, String => a, *] to _find String and save it to a local variable a) and one-line 1 in a syntax are deemed experimental in Ruby 3.0 and may change their behavior in the future_

Methods

There are quite a lot of new methods, some of which got introduced in Ruby 3.0, some earlier.

Opal 1.2: - {Random,SecureRandom}#{hex,base64,urlsafe_base64,uuid,random_float,random_number,alphanumeric} - String#{[email protected],[email protected]} - Hash#except! - {Array,Hash,Struct}#{deconstruct,deconstruct_keys}

Opal 1.1: - Array#{difference,intersection,union} - Enumerable#{filter_map,tally} - Kernel#then - {Proc,Method}#{<<,>>} - Integer#to_d

Breaking changes

Since Opal 1.2, we now follow the Ruby 3.0 semantics for Array#{to_a,slice,[],uniq,*,difference,-,intersection,&,union,|} and therefore those don't return an Array subclass anymore, but simply an Array.

What isn't there

We are still using keyword arguments in the Ruby 2.6 style. We want the future releases to warn on the incompatibilities, just like Ruby 2.7 did, to provide a smooth migration curve.

Ractor isn't implemented and likely won't be anytime soon. JavaScript has a very different threading model to Ruby.

ObjectSpace finalizer support and ObjectSpace::WeakMap implementation (Opal 1.2)

A destructor in Ruby? And also in a niche JavaScript Ruby implementation? Yes!

You need to do `require "corelib/objectspace"` to use those features._

begin ... end while ... (Opal 1.2)

Matz doesn't like this feature as it is inconsistent with how other Ruby postfix flow control constructs work. But it looks similar to do { ... } while(...) - and this is how it works. Now, also in Opal!

Native Promises (Opal 1.2 - experimental)

When Opal was first conceived, JavaScript didn't have Promises (or they weren't so universally supported), so we made our own. Now, that Promises in JavaScript are a big thing, well integrated into the language, we made a new kind of Promise (PromiseV2), that bridges the native JavaScript promise and is (mostly) compatible with the current Opal Promise (later called PromiseV1).

By bridges I mean that conversion between JavaScript and Opal values is seamless. Just as you can pass numbers, strings or arrays between those two ecosystems, Promises (only PromiseV2) will join that pack now.

There are some slight incompatibilities which is why we include both versions, and PromiseV2 is defined as experimental. This allows us to state, that it's behavior may change in the future (until deemed un-experimental). This is so also to foster a discussion about how to best support async/await in the next release.

There's a (mostly done) CoffeeScript approach to async/await available as a patch (not in the 1.2 release though), but we may as well take a different approach.

To use PromiseV2, require "promise/v2" and call PromiseV2.

Promise will become aliased to PromiseV2 instead of how it's currently aliased to PromiseV1 in Opal 2.0. You can require "promise/v1" and call PromiseV1 if you are certain that you want to stay with the old Promise. We will take a similar approach to redesigning other APIs (like NativeV2, BufferV2, etc.) in the upcoming minor releases.

The libraries in our ecosystem will soon be updated to use PromiseV2 if it's loaded instead of the PromiseV1. Do note, that PromiseV1 and PromiseV2 aren't to be mixed together, in your application you should pick one or the other. We suggest using Promises in your libraries this way:

module YourApp
  Promise = defined?(PromiseV2) ? PromiseV2 : Promise

  def using_promise
    Promise.value(true).then do
      ...
    end
  end
end

Other changes and statistics

Performance

Based on the statistics we made, Opal (both the runtime and the compiler) used to decrease in performance the more compatible with Ruby it became. This is not the case this time, we made quite a lot of performance improvements in this release. Opal 1.2 is more performant than 1.1 for many real world uses, and similar in performance to Opal 1.0. We will try to continue this trend in the future releases.

Issues

Opal 1.2 is mostly a bugfix release. We fixed a lot of long-standing bugs. Maybe it's time to try Opal again? Here we have a chart:

Issues chart

Roadmap

We didn't fully meet the expectations of the roadmap as described in the Opal 1.0 post. Better than postpone the Opal 1.1 release, we decided to release what we have (and we had quite a lot).

We have partially accomplished the code minification with an external (and experimental) opal-optimizer gem.

There are solutions for Webpack integration, but those aren't upstream. We want to gladly invite anyone interested to contribute during the Opal 1.3 development phase which we mainly want to dedicate towards accomplishment of that goal.

Opal 2.0 will hide Ruby methods behind a (JavaScript) symbol wall increasing compatibility with JavaScript libraries.

String are still immutable, (Regexps are still somewhat incompatible)[https://opalrb.com/blog/2021/06/26/webassembly-and-advanced-regexp-with-opal/], asynchronous methods can't be implemented in a Ruby synchronous style. Those features we plan for Opal 2.0 or later on, as they will require a lot of changes.

Ecosystem

All Gems from the opal-* namespace are compatible with the Opal 1.2 release. The new opal-browser version is up for a release soon, until then, we recommend you use the master branch!

From the outside of the core ecosystem, we have seen quite a lot of development, there are at least a few very interesting things that were done using Opal:

  • Glimmer DSL for Opal - an (experimental) platform-agnostic (web with Opal, desktop with SWT or Tk) toolkit for graphical applications. Write once, run anywhere!
  • 18xx.games - a website where you can play async or real-time 18xx games
  • Hyperstack - a well documented and stable Ruby DSL for wrapping React and ReactRouter as well as any JavaScript library or component. No need to learn JavaScript!

Conclusion

If you are unsure yet, Opal doesn't just feel like Ruby, it IS Ruby. It is absolutely possible to create a website with pure Ruby and not a single line of JavaScript (and a good performance!). In the advent of solutions like Hotwire, Opal goes a step higher and allows you to create fully isomorphic websites (with a fully fledged support for human language alike DSLs). Forget context switches from JavaScript, TypeScript, or even CoffeeScript to Ruby when you develop a feature, it's all Ruby!

If you are daring, you can even hook up the Opal compiler - written in a very clean Ruby - to add macro facilities to accommodate your application!

WebAssembly and advanced regular expressions with Opal

(This is a guest-post from the people at Interscript, featuring an in-depth account of the work done around building a web-assebly bridge and compiling Onigmo for Opal)


At Ribose Inc we develop Interscript, an open source Ruby implementation of interoperable transliteration schemes from ALA-LC, BGN/PCGN, ICAO, ISO, UN (by UNGEGN) and many, many other script conversion system authorities. The goal of this project is to achieve interoperable transliteration schemes allowing quality comparisons.

We decided to port our software to JavaScript using Opal (the Ruby to JavaScript compiler), so it can be also used in web browsers and Node environments. The problem is - Opal translates Ruby regular expressions (upon which we rely quite heavily) to JavaScript almost verbatim. This made our ported codebase incompatible on principle, so we searched for a better solution.

Unfortunately, Regexp is basically something like a programming language that has more than a dozen of incompatible implementations - even across the web browsers. For instance, we need lookbehind assertions, but even if there is a new standard in ECMAScript which adds lookbehind assertions, Safari doesn't implement that.

Given all this context let's dive into how we ported the original Ruby Regexp engine to the browser!

Onigmo

We started by trying to compile Onigmo with WebAssembly.

Onigmo is a Regexp engine that is used by Ruby. It is a fork of Oniguruma, which is also in use by PHP and a few more programming languages. Fortunately, it's possible to compile it to a static WebAssembly module which can be interfaced with the JavaScript land.

We tried compiling Onigmo using a simple handcrafted libc with no memory management so as to reduce the size, but this plan backfired, and rightfully so!

Now we use wasi-libc. WASI stands for WebAssembly System Interface, and is designed to provide "a wide array of POSIX-compatible C APIs".

The library is made to be able to work with both wasi-libc and the handcrafted libc, but use of wasi-libc is highly encouraged. As we are concerned about the output size of the resulting WASM binaries, we chose not to use Emscripten, just the upstream LLVM/Clang and its WASM target.

Opal-WebAssembly

After getting Onigmo, we noted, that the WebAssembly interface doesn't map 100% between C and JS. We can't pass strings verbatim and we need to do memory management (think: pointers). Is there a better solution for that than writing an Opal library to interface WebAssembly libraries?

The library is divided in two parts: there's a simple WebAssembly interface and there's a Ruby-FFI compatible binding that works on everything memory related and brings the C functions to seamlessly work with the Ruby (Opal actually) workflow.

The library has advanced beyond just being usable for this project. It should be quite compatible with Ruby-FFI allowing C API bindings across all Ruby implementations. There are some minor incompatibilities though.

Ruby-FFI assumes a shared memory model. WebAssembly has different memory spaces for a calling process and each library (think about something like a segmented memory). This makes some assumptions false.

For instance, for the following code, we don't know which memory space to use:

FFI::MemoryPointer.new(:uint8, 1200)

This requires us to use a special syntax, like:

LibraryName.context do
  FFI::MemoryPointer.new(:uint8, 1200)
end

This context call makes it clear that we want this memory to be alocated in the "LibraryName" space.

Another thing is that a call like the following:

FFI::MemoryPointer.from_string("Test string")

Would not allocate the memory, but share the memory between the calling process and the library. In Opal-WebAssembly we must allocate the memory, as sharing is not an option in the WASM model. Now, another issue comes into play. In regular Ruby a call similar to this should allocate the memory and clear it later, once the object is destroyed. In our case, we can't really access JavaScript's GC. This means we always need to free the memory ourselves.

Due to some Opal inadequacies, we can't interface floating-point fields in structs. This doesn't happen in Onigmo, but if needed in the future, a pack/unpack implementation for those will be needed.

Chromium browser doesn't allow us to load WebAssembly modules larger than 4KB synchronously. This means that we had to implement some methods for awaiting the load. This also means, that in the browser we can't use the code in a following way:

<script src='file.js'></script>
<script>
  Opal.Library.$new();
</script>

This approach works in Node and possibly in other browsers, but Chromium requires us to use promises:

<script src='file.js'></script>
<script>
  Opal.WebAssembly.$wait_for("library-wasm").then(function() {
    Opal.Library.$new();
  });
</script>

There are certain assumptions of how a library should be loaded on Opal side - the FFI library creation depends on the WebAssembly module being already loaded, so we need to either move those definitions to a wait_for block or move require directives, like so:

WebAssembly.wait_for "onigmo/onigmo-wasm" do
  require 'interscript'
  require 'my_application_logic'
end

The source for opal-webassembly is available at https://github.com/interscript/opal-webassembly.

Opal-Onigmo

After having a nice library to bind with WebAssembly modules, writing an individual binding was very easy and the resulting code looks (in my opinion) very cool.

Our initial plan assumed upstreaming the code later on. I don't think it will be possible or healthy. This library should stay as a separate gem for a couple of reasons.

First is that due to the memory issues, we aren't able to make it work as a drop-in replacement. We need to manually call an #ffi_free method. Eg:

re = Onigmo::Regexp.new("ab+")
# use the regular expression
re.ffi_free # free it afterwards and not use it anymore

At early stages our implementation of Opal-Onigmo we didn't consider the memory a problem. When hit with a real world scenario, we found out, that it's a severe issue and needs to be dealt with. As far as we know, the library doesn't leak any memory if the regular expression memory is managed correctly.

The second is that after all, we don't really have a way of caching the compiled Regexps. Furthermore, Onigmo compiled with WASM may not be as performant as the highly optimized JS regexp engine. In this case it's much better to leave it as a drop-in replacement for those who need more correctness.

Opal-Onigmo doesn't implement all the methods for Ruby Regexp, it was mostly meant for completion of the Interscript project, but can be extended beyond. It implements a few methods it needs to implement for String (this is just an option - you need to load onigmo/core_ext manually), but most of the existing ones work without a problem. We implemented a Regexp.exec (JavaScript) method, and the rest of Opal happened to mostly interface with it. At the current time we know that String#split won't "just" work, but String#{index,rindex,partition,rpartition} should.

Opal-Onigmo depends on the strings being coded as UTF-16. There are two reasons to that:

  1. Opal includes methods for getting the binary form of strings in various encodings, but only methods for UTF-16 are valid for characters beyond the Basic Multilingual Plane (Unicode 0x0000 to 0xffff) which are used in 2 maps.
  2. JavaScript uses UTF-16 strings internally.

The source for opal-onigmo is available at https://github.com/interscript/opal-onigmo.

Interscript

Using Opal-Onigmo we made it so that it passes all the tests (not counting transliterating Thai scripts which ultimately depends on an external process, which relies on machine learning). To optimize it, we use Opal-Onigmo only when the regexp is a more complex regexp, otherwise we fall back to an (ultimately faster) JavaScript regexp engine:

def mkregexp(regexpstring)
  @cache ||= {}
  if s = @cache[regexpstring]
    if s.class == Onigmo::Regexp
      # Opal-Onigmo stores a variable "lastIndex" mimicking the JS
      # global regexp. If we want to reuse it, we need to reset it.
      s.reset
    else
      s
    end
  else
    # JS regexp is more performant than Onigmo. Let's use the JS
    # regexp wherever possible, but use Onigmo where we must.
    # Let's allow those characters to happen for the regexp to be
    # considered compatible: ()|.*+?{} ** BUT NOT (? **.
    if /[\\$^\[\]]|\(\?/.match?(regexpstring)
      # Ruby caches its regexps internally. We can't GC. We could
      # think about freeing them, but we really can't, because they
      # may be in use.
      @cache[regexpstring] = Onigmo::Regexp.new(regexpstring)
    else
      @cache[regexpstring] = Regexp.new(regexpstring)
    end
  end
end

It also never frees the regexps (see a previous note about #ffi_free), because we never know if a Regexp won't be in use later on (and the Regexps are actually cached in a Hash for performance reasons). The issue about dangling Regexps can be worked out in the future, but the JS API will need to change again. We would need to do something like:

Opal.Interscript.$with_a_map("map-name", function() {
  // do some work with a map
});

This call would at the beginning allocate all the Regexps needed, and at the end, free them all. The good news is that we would be able to somehow integrate loading transliteration maps from the network (along with dependencies) with such a construct.

The future

Post writing this article we noted that JavaScript actually does implement a construct that would work like a destructor, allowing us to free the allocated memory dynamically. Unfortunately, that's the latest ECMAScript addition, which means there are still environments that don't support it (Safari) and there is one that needs an explicit flag (Node 13+).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry

We could use it to implement some parts of ObjectSpace of Ruby and then use it in opal-webassembly to free memory on demand.

Afterwords

This article was written long before it was published. Since then, Interscript was rewritten to a totally different architecture and doesn't use Opal anymore. We don't use Regexps directly anymore, but we created a higher-level (Ruby) DSL to describe the transliteration process that we compile directly to a highly-optimized pure Ruby/JavaScript code (and it can be extended to other languages as well). Ribose Inc still uses Opal in other projects, for example to build Latexmath, a library that converts LaTeX math expressions to MathML, as a JavaScript library. We also contribute fixes back to the upstream Opal project.

For the Opal project, all this effort serves as an interesting experiment to establish further guidelines should we decide to increase Regexp compatibility in the future and can serve as a useful tool for anyone wanting to port his Ruby codebase with a heavy regexp use to JavaScript. It should also facilitate porting libraries that use Ruby-FFI currently.

The libraries we created are available under a 2-clause BSD license in the following repositories:

  • https://github.com/interscript/Onigmo - Onigmo port to WebAssembly
  • https://github.com/interscript/opal-onigmo - the Onigmo interface to Opal
  • https://github.com/interscript/opal-webassembly - the FFI-like interface to Opal, using WebAssembly
  • https://github.com/interscript/interscript/tree/v1 - the obsolete v1 branch of Interscript that used Opal and Opal-Onigmo

Opal 1.0

Dear Opalists of the world,
the time has come, 1.0 has been released!

This is, of course, a really important milestone, one that I've been waiting on for about seven years. I started advocating for releasing version 1.0 back in 2012 when Opal was still at version 0.3. After all, at that time I already had code in production, and according to Semver (which by then was still a new thing) that's one of the criteria for releasing 1.0:

How do I know when to release 1.0.0?

If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backward compatibility, you should probably already be 1.0.0.

https://semver.org/#how-do-i-know-when-to-release-100

I was so proud and excited about this ability to use Ruby for frontend code! I was writing the logic for an in-page product filter and Ruby allowed me to solve the problem quickly, with its signature concise syntax, and leveraging the power of enumerable. That immensely reduced the lines of code I had to write and allowed me to concentrate on just the core of the problem.

Many years have passed, and I'm even more proud of the project that Opal has become, the maturity and the feature parity with MRI is astounding, the new features that are coming in version 1.0 are even more amazing, and the roadmap ahead makes Opal one of the best choices among compile-to-JS languages.


Before diving into each new feature I'd like to give immense credit for the MVP of this release, namely our good Ilia Bylich! Without his unrelenting work and deep understanding of Ruby, we wouldn't be where we are. Thanks man! 👏👏👏

Notable New Features

continue reading…

Opal-RSpec v0.7, has been finally released! ✨

It's been a deep work of refactoring and rewriting, adding specs and updating dependencies. Huge kudos to @wied03 for the foundational work and as usual to @iliabylich for the laser sharp refactoring.

For a full list of changes and updated instructions please checkout the Changelog and the Readme.

New opal-rspec command

A new CLI executable has been added with basic functionality to aid writing and running specs. Type opal-rspec -h for the complete list of options.

One notable addition is the --init option that will help you initialize your project with opal-rspec.

New folder defaults 📂

With this update I'm also announcing the new standard paths for opal lib/ and spec/ folders, which are lib-opal/ and spec-opal. This will avoid the confusion about the role of the two folders and make them nicely stay near they're MRI counterparts in your editor.

In this spirit the opal-rspec command and all rake tasks will look for spec files in spec-opal/.

Note: those defaults are intended as the current best practice to organize an Opal project.


🗓 More than a year has passed since the last post, if you missed Opal, that's because most of the news circulated on the Slack channel, that's my fault! But rejoice! new posts are coming and the 1.0 release is around the corner 😄

Link to the official chat updated on 2020/04/28.

Opal-RSpec 0.5: Newer RSpec version, improved Rake task, better documentation

Opal-RSpec

If you're a Rubyist, you know about RSpec. It's the testing framework that most of us like. RSpec's code base also happens to use a lot of features of the Ruby language, which means getting it to work on Opal is a challenge, but to some extent, we're there! Even if you're writing code in ES5/ES6, you might enjoy using RSpec as an alternative to Jasmine. Opal's native JS functionality makes that fairly easy to do.

What's new?

There were 394 commits since opal-rspec 0.4.3 that covered a variety of areas:

  • Opal itself - 30+ pull requests went into Opal 0.9 to improve RSpec's stability on Opal. This obviously benefits anyone using opal, not just opal-rspec users.
  • RSpec specs - opal-rspec 0.5 now runs and passes 80%+ of RSpec's own specs. For the first time, limitations, including some present in prior opal-rspec versions, are documented.
  • New versions - Base RSpec version has been upgraded to 3.1 from the 3.0 beta (we know we're still behind, but read on) and the Rake task works with Phantom JS 1.9.8 and 2.0.
  • New features - Node runner support and improved Rake task configurability.

How do you get started?

First step is adding it to your Gemfile and bundle install.

gem 'opal-rspec'

Then you'll need to ensure, for the default config, you have at 1.9.8 of PhantomJS installed.

Then you can start writing specs!

Put this in spec/42_spec.rb

describe 42 do
  subject { 43 }

  it { is_expected.to eq 43 }
end

Then in your Rakefile:

require 'opal/rspec/rake_task'
Opal::RSpec::RakeTask.new(:default)

After running bundle exec rake, you'll see:

Running phantomjs /usr/local/bundle/gems/opal-rspec-0.5.0/vendor/spec_runner.js "http://localhost:9999/"
Object freezing is not supported by Opal

.

Finished in 0.013 seconds (files took 0.163 seconds to load)
1 example, 0 failures

Right off the bat, you can see at least a few things Opal doesn't like about RSpec's code base (the freeze warning), but as of opal-rspec 0.5, those are either limited to this warning message or other documented limitations.

Formatter support works as well.

After running SPEC_OPTS="--format json" bundle exec rake:

Object freezing is not supported by Opal

{"examples":[{"description":"should eq 43", "full_description":"42 should eq 43", "status":"passed", "file_path":"http://localhost", "line_number":9999, "run_time":0.005}], "summary":{"duration":0.013, "example_count":1, "failure_count":0, "pending_count":0}, "summary_line":"1 example, 0 failures"}

Asynchronous testing on Opal

Since opal has a promise implementation built in, opal-rspec has some support for asynchronous testing. By default, any subject, it block, before(:each), after(:each), or around hook that returns a promise will cause RSpec to wait for promise resolution before continuing. In the subject case, any subject resolution in your specs will be against the promise result, not the promise, which should DRY up your specs.

Example: Create spec/async_spec.rb with this content:

describe 'async' do
  subject do
    promise = Promise.new
    delay 1 do
      promise.resolve 42
    end
    promise
  end

  it { is_expected.to be_a Promise }
  it { is_expected.to eq 42 }
end

Result:

Running phantomjs /usr/local/bundle/gems/opal-rspec-0.5.0/vendor/spec_runner.js "http://localhost:9999/"
Object freezing is not supported by Opal

.F.

Failures:

  1) async should be a kind of Promise
     Failure/Error: Unable to find matching line from backtrace
     Exception::ExpectationNotMetError:
       expected 42 to be a kind of Promise
     # ExpectationNotMetError: expected 42 to be a kind of Promise
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:4294
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:50378
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:33927
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:33950
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:33708
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:53200
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:3000
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:52274
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:52348
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:1055
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:14805
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:52554
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:52573
     #     at http://localhost:9999/assets/opal/rspec/sprockets_runner.js:52555
     #
     #   Showing full backtrace because every line was filtered out.
     #   See docs for RSpec::Configuration#backtrace_exclusion_patterns and
     #   RSpec::Configuration#backtrace_inclusion_patterns for more information.

Finished in 2.03 seconds (files took 0.156 seconds to load)
3 examples, 1 failure

Failed examples:

rspec http://localhost:9999 # async should be a kind of Promise

The failure is because we get a number back, not a Promise.

Other new tools in the ecosystem

JUnit & TeamCity/Rubymine formatter support

The chances are your CI tool supports at least 1 of those. Check out opal-rspec-formatter

Karma support

If you want to tap into the browser runners that Karma supports but keep using Opal, you might want to check out karma-opal-rspec.

Work to be done

As was mentioned above, we're still using RSpec 3.1, which as of this writing, is almost 1.5 years old. Due to the number of changes necessary to make RSpec Opal friendly, we cannot track with RSpec releases as fast as we would like. That said, several things we're doing should allow us to move faster in the future, including:

  • Constantly improving Opal code base that allows more Ruby features to work out of the box.
  • RSpec specs which helped improve Opal and allow us to easily identify far corners of RSpec's functionality.
  • Work on arity checking is already in-progress (opal-rspec currently doesn't run with arity checking enabled). This will tease out even more issues.

All of these will eventually lead to less monkey patching and more out of the box stuff that works.

How to help

Arity checking is the top priority right now. If you can assist with issues like this opal issue that are documented on the opal-rspec arity check issue, that will help move things along.

After that is complete, we can begin work on RSpec 3.4.

Opal 0.10: Rack 2 compatibility, improved keyword argument support, better source maps, and a whole lot more

Opal is now officially on the 0.10.x release path. Thanks to all the contributors to Opal who've worked hard to make this release possible. Some highlights from the latest release:

  • Improvements to source maps
  • Updates to methods in Array, Enumerable, and Module for RubySpec compliance
  • Rack v2 compatibility
  • Support for keyword arguments as lambda parameters, as well as keyword splats
  • Some IO enhancements to better work with Node.js
  • Marshalling support continue reading…

Opal 0.9: direct JS calls, console.rb, numeric updates, better reflection, and fixes aplenty

Opal is now officially on the 0.9.x release path, having just released 0.9.2. Thanks to all the contributors to Opal, especially over the holidays, and we're excited for what the new year will bring to the Opal community. Some highlights from the latest release:

Direct calling of JavaScript methods

You can now make direct JavaScript method calls on native JS objects using the recv.JS.method syntax. Has support for method calls, final callback (as a block), property getter and setter (via #[] and #[]=), splats, JavaScript keywords (via the ::JS module) and global functions (after require "js").

Some examples, first a simple method call:

# javascript: foo.bar()
foo.JS.bar
foo.JS.bar()
continue reading…

Opal 0.7.0: require, kwargs, docs, testing, lots of fixes

It's been almost a year from our 0.6.0 release and has been an awesome time for the Opal community. Today I'm proud to announce we have released v0.7.0, which comes packed with lots of good stuff and uncountable bug fixes.

#require #require_relative and #require_tree

The require system has been completely overhauled in Opal 0.7. The previous version was a rather smart wrapper around sprockets directives but had some limitations, especially when it came to interleaving require calls and code. Some gems couldn't be compiled with Opal just for that reason.

The new require system now relies on a module repository where each "module" actually corresponds to a Ruby file compiled with Opal. This means that #require calls aren't no-ops anymore.

In addition to that #require_relative support has been added and for feature parity with sprockets directives we're also introducing #require_tree. The latter will be particularly useful to require templates.

Keyword Arguments

This has been a super requested feature, and thanks to Adam Beynon they're now a reality. They still have some rough edges (as they did in their first CRuby/MRI incarnation) but the core is there for you all to enjoy.

continue reading…

Promises: Handling asynchronous code in Opal

When using Opal, one large omission from the stdlib are Threads. This is because javascript does not have threads, which makes asyncronous programming difficult in ruby. As javascript has increased in popularity with DOM libraries and web frameworks, callback hell was the standard way to handle asynchronous events in javascript. This was also the way events were handled in Opal applications. Until now.

What is so great about promises?

When looking at a simple example, the benefits of promises may not be obvious:

# old callback method
HTTP.get("url") do |response|
  puts "got response"
end

# using promises
HTTP.get("url").then do |response|
  puts "got response"
end

Initially the method call using a Promise looks just a more verbose version of the standard callback approach. The benefit of promises come through when promises are chained together. The result of the #then call actually returns a new Promise instance, which will not be resolved until the result of the first block resolves itself.

Callback hell

Lets take a slightly more complex example where an initial HTTP request is made for some user details, and then a second request is made using the result of the first json response:

continue reading…