There's opal-irb
and opal-jquery
and vienna
but is there any way to use gems directly in the browser via 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:
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.
来源:https://stackoverflow.com/questions/24573142/can-i-use-ruby-gems-in-opal