Wednesday, January 12, 2022

Using Opal Ruby with Rails 7

Opal enables writing web front-end code in Ruby, thus producing highly maintainable, productive, and understandable code on both the client-side and server-side.

Below, I present 3 different examples of using Opal Ruby on Rails 7.

Basic Opal Rails 7 Example

Rails 7 recently came out with simplified defaults, including defaulting back to Sprockets.

Setting up Opal on Rails 7 is a breeze as a result.

You may follow these instructions to get a Hello, World! Opal example running in Rails 7:

Advanced Opal Rails 7 Example

Next, let's build a complete Rails application using Opal Ruby instead of JavaScript, called Baseball Cards!

It will be an animated baseball card creation application that simply takes a player name, team, and position, and renders a baseball card live while information is typed into a WYSIWYG form. 

The form looks up random player animated gifs on Giphy. If you do not like the randomly selected photo, you can click the "Another Player Image" button to change it. Otherwise, the form also adds an image for the selected baseball team logo and it edits an SVG element live that represents the player position (e.g. if the player is a 1st-base position player, that part of the SVG lights up yellow). Here is how the "New baseball card" form looks like:

Normally, JavaScript must be involved to interactively build the Baseball Card, but thanks to Opal, we can write most of the code in pure Ruby instead. Note that some Opal Native code was mixed in as well (that is using ticks `` to execute small bits of JS inside the Ruby code just like when you use ticks `` in CRuby to shell out into the command line terminal), thus demoing this Opal capability too.

The code solution is included below (note that since it is just a demo, I mostly embedded CSS in the elements in the `_baseball_card.html.erb` partial).

Opal jQuery Example

Next, let's refactor the code to utilize Opal jQuery in Ruby instead of plain Opal. This simplifies the code in `app/assets/javascript/application.js.rb` quite a bit:

The same app should continue working, but with more maintainable Opal jQuery Ruby code!

A canonical version of the project is available at GitHub:

Also, hosted on Heroku:


No comments: