Let's try Opal. I don't want to setup a Rails application. Just static html with javascript written in Opal, stylesheets in SASS, and HTML in Slim. Also we want to use JQuery like methods to select DOM elements. We use sprockets, an assets pipeline from rails, and rails-assets to manage javascript libraries.
Let's set this thing up!
mkdir opal-playground
$ cd opal-playground
$ bundle init $
Bundler initialized, lets add some gems, edit Gemfile
:
"https://rubygems.org"
source
'https://rails-assets.org' do
source 'rails-assets-jquery'
gem end
'opal'
gem 'opal-jquery'
gem 'slim'
gem 'sass' gem
and install gems
bundle $
We need to create four folders:
Sprockets uses rack to serve compiled assets, lets make a config.ru
for that:
'bundler'
require Bundler.require
Sprockets::Environment.new.tap do |s|
sprockets =
# register slim
'.slim', Slim::Template
s.register_engine
# register opal
'.rb', Opal::Processor
s.register_engine
# add folders
'app'
s.append_path 'views'
s.append_path 'styles'
s.append_path
# add paths from opal
Opal.paths.each do |p|
s.append_path pend
# add paths from rails-assets
RailsAssets.load_paths.each do |p|
s.append_path pend
end
Opal::Processor.source_map_enabled = false
'/' do
map
run sprocketsend
Let start with views/index.html.slim
file:
doctype html
html
head
title Hello
link href='style.css' rel='stylesheet' type='text/css'
script src='app.js'
body
h2#element
button#button ClickMe
Simple, include style.css
stylesheet, and app.js
for javascriptis. Create a styleshet styles/style.css.sass
:
body h2
color: red
Finally we can create ruby (opal) file app/app.js.rb
:
# use sprockets directive to include jquery
#= require 'jquery'
'opal'
require 'opal-jquery'
require
Document.ready? do
# checkout browser console
"Message from opal"
puts
# add some text to h2
Element.find('#element').text = "Setting header with Opal"
# onclick event
Element.find('#button').on :click do
Element.find('#element').text = "Button Clicked!"
end
end
We're done, is this working ?
rackup $
And open http://localhost:9292/index.html! Happy?
You're lazy ? Check out github repository or simply:
git clone git@github.com:fazibear/opal-slim-sass-sprockets-example.git $