0

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?

andreheijstek
  • 71
  • 1
  • 9
  • How are you compiling the ruby code? Maybe you're loading the Opal code from the CDN? – Elia Schito Nov 19 '18 at 00:28
  • I'm compiling the code in a rakefile like this: `File.open("app/blokouderling_lookup.js", "w+") do |out| out << Opal.compile(File.read('app/blokouderling_lookup.rb'))` The js code runs inside a Wordpress site. In there I've uploaded the latest opal code. – andreheijstek Nov 21 '18 at 16:49
  • My advice is to use `Opal::Builder` and produce a single file for everything in it like in the answer below – Elia Schito Nov 22 '18 at 23:30

1 Answers1

0

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.

Elia Schito
  • 989
  • 7
  • 18