- Notifications
You must be signed in to change notification settings - Fork69
Bringing Ruby to Rails · Rails bindings for Opal
opal/opal-rails
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Rails bindings forOpal. (Changelog)
If you want to integrate Opal via Webpack please refer toopal-webpack-loader installation instructions.
ℹ️ Webpack and ES6 modules are not yet officially supported, but we're working on it thanks to the awesome work done inopal-webpack-loader.
In yourGemfile
gem'opal-rails'
Runopal:install Rails generator to addapp/assets/javascript to your asset-pipeline manifest inapp/assets/config/manifest.js:
bin/rails g opal:installThe following automatically gets added to your configuration for the compiler when running theopal:install Rails generator:
config/initializers/opal.rb
# Compiler optionsRails.application.configuredoconfig.opal.method_missing_enabled=trueconfig.opal.const_missing_enabled=trueconfig.opal.arity_check_enabled=trueconfig.opal.freezing_stubs_enabled=trueconfig.opal.dynamic_require_severity=:ignoreend
Check out the full list of the available configuration options at:lib/opal/config.rb.
You may optionally add configuration for rendering assigns when using the template handler from actions:
config/initializers/opal.rb
Rails.application.configuredo# ...config.opal.assigns_in_templates=trueconfig.opal.assigns_in_templates=:locals# only localsconfig.opal.assigns_in_templates=:ivars# only instance variablesend
Local and instance variables will be sent down to the view after converting their values to JSON.
This example assumes Rails 7 and having followed theInstallation instructions.
1- Deleteapp/javascript/application.js
2- Enable the following lines in the generatedapp/assets/javascript/application.js.rb belowrequire "opal":
puts"hello world!"require"native"$$[:document].addEventListener:DOMContentLoadeddo $$[:document][:body][:innerHTML]='<h2>Hello World!</h2>'end
3- Runrails g scaffold welcome
4- Runrails db:migrate
5- Clearapp/views/welcomes/index.html.erb (empty its content)
6- Runrails s
7- Visithttp://localhost:3000/welcomes
In the browser webpage, you should see:
Also, you should seehello world! in the browser console.
This example assumes Rails 5.
- Rename
app/assets/javascripts/application.jstoapp/assets/javascripts/application.js.rb - Replace the Sprockets directives with plain requires
# Require the opal runtime and core libraryrequire'opal'# For Rails 5.1 and above, otherwise use 'opal_ujs'require'rails_ujs'# Require of JS libraries will be forwarded to sprockets as isrequire'turbolinks'# a Ruby equivalent of the require_tree Sprockets directive is availablerequire_tree'.'puts"hello world!"
require'opal'require'opal_ujs'require'turbolinks'require_tree'.'# a Ruby equivalent of the require_tree Sprockets directive is available# ---- YOUR FANCY RUBY CODE HERE ----## Examples:# == Print something in the browser's consoleputs"Hello world!"pphello::worldrequire'console'$console.log%w[Helloworld!]# == Use Native to wrap native JS objects, $$ is preconfigured to wrap `window`require'native'$$.alert"Hello world!"# == Do some DOM manipulation with jQueryrequire'opal-jquery'Document.ready?doElement.find('body').html='<h1>Hello world!</h1>'end# == Or access the DOM api directly$$[:document].addEventListener(:DOMContentLoaded,->{ $$[:document].querySelector('body')[:innerHTML]='<h1>Hello world!</h1>'})
If you want to useapplication.js (instead ofapplication.js.rb) and keep using Sprockets directives, you'll need to load the Opal files you require via Sprockets manually, e.g.:
//= require opal//= require rails_ujs//= require turbolinks//= require_tree .//= require appOpal.require('opal');Opal.require('app');
You can use it for your views too:
# app/controllers/posts_controller.rbdefcreate@post=Post.create!(params[:post])rendertype::js,locals:{comments_html:render_to_string(@post.comments)}end
Assigned instance that would normally be available in your views are converted to JSON objects first.
# app/views/posts/create.js.opalpost=Element.find('.post')post.find('.title').html=@post[:title]post.find('.body').html=@post[:body]post.find('.comments').html=comments_html
By defaultopal-rails, will NOT forward any instance and local variable you'll pass to the template.
This behavior can be enabled by settingRails.application.config.opal.assigns_in_templates totrue inconfig/initializers/assets.rb:
Rails.application.configuredo# ...config.opal.assigns_in_templates=true# ...end
Of course you need to requirehaml-rails separately since its presence is not assumed
-# app/views/posts/show.html.haml%article.post %h1.title= post.title.body= post.body%a#show-comments Display Comments!.comments(style="display:none;") - post.comments.each do |comment|.comment= comment.body:opal Document.ready? do Element.find('#show-comments').on :click do |click| click.prevent_default click.current_target.hide Element.find('.comments').effect(:fade_in) end end
Extracted to (unreleased)opal-rspec-rails
Add this line to yourGemfile:
gem'opal-rspec-rails',github:'opal/opal-rspec-rails'
Upcoming asopal-minitest-rails
As long as the templates are inside the Sprockets/Opal load path, then you should be able to just require them.
Let's say we have this templateapp/views/shared/test.haml:
.row.col-sm-12 = @bar
We need to make sure Opal can see and compile that template. So we need to add the path to sprockets:
# config/initializers/opal.rbRails.application.config.assets.paths <<Rails.root.join('app','views','shared').to_s
Now, somewhere inapplication.rb you need to require that template, and you can just run it throughTemplate:
# app/assets/javascripts/application.rbrequire'opal'require'opal-haml'require'test'@bar="hello world"template=Template['test']template.render(self)# => '<div><div>hello world</div></div>'
Just useOpal.use_gem in your asset initializer (config/initializers/assets.rb).
Example:
Opal.use_gem'cannonbol'
Run the specs:
bin/setupbin/rakeInspect the test app:
bin/rackup# visit localhost:9292Tinker with a sandbox app:
bin/sandbox # will re-create the appbin/rails s # will start the sandbox app server# visit localhost:3000© 2012-2024 Elia Schito
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.About
Bringing Ruby to Rails · Rails bindings for Opal
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.