Can I use Ruby gems in Opal?

余生颓废 提交于 2019-12-06 00:30:56

问题


There's opal-irb and opal-jquery and vienna but is there any way to use gems directly in the browser via Opal?


回答1:


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




回答2:


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 Strings), but within these limits you may share your code between the server and the client.



来源:https://stackoverflow.com/questions/24573142/can-i-use-ruby-gems-in-opal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!