简体   繁体   中英

Can I use Ruby gems in Opal?

opal-irbopal-jqueryvienna但有没有办法通过Opal直接在浏览器中使用宝石?

You can add a gem's lib path to Opal load paths by using Opal.use_gem

Common pitfalls are:

  • use of String mutability
  • relying on the difference between String and Symbol
  • shelling out ( `` and %x{} )

Available tools to fix/workaround some of those issues are:

  • stubbing files Opal::Processor.stub_file('fileutils')
  • hiding code branches at compile time using RUBY_ENGINE , example: unless RUBY_ENGINE == 'opal' unparsable/breaking code here end

You can look at the opal-rspec source code to see this stuff in action:

https://github.com/opal/opal-rspec

As usual the answer is yes and no at the same time, depending on your point of view. Opal will turn your ruby ( all of it) into JavaScript and provides an appropriate run time. If you require a gem it will be required during the compilation process and will be included into the generated JavaScript. You may freely use the generated ruby classes in your ruby code (which again ends up being compiled into JavaScript).

So you can require gems, but bear in mind that their requires will also be required, so will end up with a nightmare of a JavaScript file if you are not careful. Technically you are still not running ruby in the browser, it all had to be compiled to JavaScript for that purpose. However you can run the code generated from your ruby and the required gems, though it will have become JavaScript during the process (and you will have to debug it as such). There are some limitations to this approach though, you will have to bear in mind JavaScript Number and String properties (aka only immutable String s), but within these limits you may share your code between the server and the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM