I get an JS error Opal.const_get_relative is not a function when compiling ruby into js

83 Views Asked by At

I have a Ruby function translated into JS by Opal that has always worked fine, but suddenly it does not work anymore. The JS console gives me this error message

Opal.const_get_relative is not a function

The original Ruby code is this

Document.ready? do
  Element.find('#button_id').on :click do

Which translates into this

  return $send(Opal.const_get_relative($nesting, 'Document'), 'ready?', [], (TMP_1 = function(){var self = TMP_1.$$s || this, TMP_2;

  return $send(Opal.const_get_relative($nesting, 'Element').$find("#button_id"), 'on', ["click"], (TMP_2 = function(){var self = TMP_2.$$s || this, TMP_3, postcode_value = nil, blokouderling = nil, content = nil, wijk = nil, naam = nil, email = nil, $writer = nil;

Any idea what goes wrong?

1

There are 1 best solutions below

0
On

The easiest way to compile an opal app to a file outside of Rails is to build the JavaScript file with Opal::Builder, here's a simple example with both Opal and jQuery:

gem 'opal', '~> 0.11.4'
gem 'opal-jquery', '~> 0.4.3'

require 'opal'
require 'opal-jquery'

app_html = <<-HTML
  <html><head>
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  <script src="app.js"></script>
  </head><body></body></html>
HTML

app_code = <<-RUBY
  Document.ready? do
    alert('hello world!')
  end
RUBY

builder = Opal::Builder.new
builder.build('opal')
builder.build('opal-jquery')
builder.build_str app_code, 'app.rb'

File.write 'app.js', builder.to_s
File.write 'app.html', app_html

At that point you can just open app.html with your browser to see the "hello world" message popping up in an alert.