DEV Community

Cover image for Introducing OpalStimulus! ๐ŸŽ‰
Joseph Schito
Joseph Schito

Posted on • Edited on

Introducing OpalStimulus! ๐ŸŽ‰

Have you ever dreamed of being able to write your Stimulus controllers in Ruby instead of JavaScript?
Here's OpalStimulus, a Stimulusjs wrapper for Opal, with a Rails installer.
Obviously for now (while being functional) this project is still in development and not complete, but if you want to contribute or simply try it out, you can do so https://github.com/josephschito/opal_stimulus/pulls

Here's a small example of how it works:

Basic Example

Here's a Hello World example with OpalStimulus. Compare with the original Stimulus example.

Add this line to your Gemfile:

gem 'opal_stimulus'
Enter fullscreen mode Exit fullscreen mode

Run:

bundle install
rails generate opal_stimulus:install
Enter fullscreen mode Exit fullscreen mode

Start the application:

bin/dev
Enter fullscreen mode Exit fullscreen mode

Create app/opal/controllers/hello_controller.rb and fill it with:

class HelloController < StimulusController
  self.targets = ["name", "output"]
  def greet
    output_target.text_content = "Hello, #{name_target.value}!"
  end
end
Enter fullscreen mode Exit fullscreen mode

Add this to a view:

<div data-controller="hello">
  <input data-hello-target="name" type="text">
  <button data-action="click->hello#greet">
    Greet
  </button>
  <span data-hello-target="output">
  </span>
</div>
Enter fullscreen mode Exit fullscreen mode

Result:

Enjoy! ๐Ÿ˜‰

Top comments (5)

Collapse
 
nevodavid profile image
Nevo David

honestly this is huge for me since i never vibe with js that much. makes me wonder - you think stuff like this actually helps keep dev life fun, or does it just make us lazier over time?

Collapse
 
josephschito profile image
Joseph Schito

Thank you for your interest!
I always recommend learning a bit of JavaScript if you want to work with the DOM.
I had a lot of fun creating this gem, and I think a more stable version could be beneficial for those who also want to have some fun.

Collapse
 
josephschito profile image
Joseph Schito
Collapse
 
sebyx07 profile image
sebyx07

too much overhead of having the code full of .JS[]

Collapse
 
josephschito profile image
Joseph Schito

I totally agree with you!
This is a very early version, Iโ€™ll definitely remove them soon.