简体   繁体   English

我可以在蛋白石中使用Ruby宝石吗?

[英]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 您可以使用Opal.use_gem将gem的lib路径添加到Opal加载路径

Common pitfalls are: 常见的陷阱是:

  • use of String mutability 使用String可变性
  • relying on the difference between String and Symbol 依赖于String和Symbol之间的区别
  • shelling out ( `` and %x{} ) 炮轰( ``%x{}

Available tools to fix/workaround some of those issues are: 修复/解决其中一些问题的可用工具包括:

  • stubbing files Opal::Processor.stub_file('fileutils') 存根文件Opal::Processor.stub_file('fileutils')
  • hiding code branches at compile time using RUBY_ENGINE , example: unless RUBY_ENGINE == 'opal' unparsable/breaking code here end 使用RUBY_ENGINE在编译时隐藏代码分支,例如: unless RUBY_ENGINE == 'opal' unparsable/breaking code here end

You can look at the opal-rspec source code to see this stuff in action: 您可以查看opal-rspec源代码以查看这些内容:

https://github.com/opal/opal-rspec 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. Opal会将您的ruby( 全部 )转换为JavaScript并提供适当的运行时间。 If you require a gem it will be required during the compilation process and will be included into the generated JavaScript. 如果您需要gem,则在编译过程中将需要它,并将包含在生成的JavaScript中。 You may freely use the generated ruby classes in your ruby code (which again ends up being compiled into JavaScript). 您可以在ruby代码中自由使用生成的ruby类(它最终会被编译成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. 因此,您可以要求宝石,但请记住,他们的要求也是必需的,因此如果您不小心,最终会导致JavaScript文件的噩梦 Technically you are still not running ruby in the browser, it all had to be compiled to JavaScript for that purpose. 从技术上讲,仍然没有在浏览器中运行ruby,为了这个目的,所有这些都必须编译为JavaScript。 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). 但是,您可以运行从ruby生成的代码和所需的gem,尽管在此过程中它将成为JavaScript(并且您必须对其进行调试)。 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. 但是这种方法存在一些限制,您必须牢记JavaScript NumberString属性(也称为只有不可变的String ),但在这些限制内,您可以在服务器和客户端之间共享代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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