opal / opal

Ruby ♥︎ JavaScript
https://opalrb.com
MIT License
4.83k stars 331 forks source link

Opal for Utility Functions #2081

Closed plainlystated closed 4 years ago

plainlystated commented 4 years ago

I'm trying to get oriented with Opal, and I'm a little lost. My use case is that I have a rails backend and vue frontend. I have a module in ruby that computes prices for stuff, and I'd like to have a client-side version of that code without actually duplicating and maintaining two copies. Opal seems like it may be a help here, but I can't figure out how to generate a JS file with some utility methods that can be called by my main (Vue) JS code.

Is this a use-case that Opal supports?

The code I'm trying to get working is:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="app.js"></script>
  </head>
  <body>
    <script>
      foo();
    </script>
  </body>
</html>

The code I'm compiling to JS:

def foo
  puts 'called foo'
end

My command:

opal -c app.rb  > app.js

...and the error I get:

ReferenceError: foo is not defined
plainlystated commented 4 years ago

Found what I was looking for here: https://opalrb.com/docs/guides/v1.0.3/compiled_ruby.html