Stimulus Sprockets

This example is based on the Stimulus site, but based on Ruby2JS instead and hosted by Ruby on Rails. It also uses the Sprockets/asset-pipeline instead of Webpacker. The Rails Guides have more information on how Sprockets is different than Webpacker.

Create a Project

Start a new project:

rails new stimulus-sprockets
cd stimulus-sprockets

Add the following lines to your Gemfile:

gem 'ruby2js', require: 'ruby2js/rails'
gem 'stimulus-rails'

Run the following commands:

./bin/bundle install
./bin/rails ruby2js:install:stimulus:sprockets

Write some HTML and a matching Stimulus controller

Generate a Rails controller:

./bin/rails generate controller Greeter hello

Add the following to app/views/greeter/hello.html.erb:

<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>

Remove app/assets/javascripts/controllers/hello_controller.js, and create app/assets/javascripts/controllers/hello_controller.js.rb with the following contents:

class HelloController < Stimulus::Controller
  def greet()
    outputTarget.textContent =
      "Hello, #{nameTarget.value} from Ruby!"
  end
end

Try it out!

Start your server:

./bin/rails server

Visit http://localhost:3000/greeter/hello. What you should see:

Browse http://localhost:3000/assets/controllers/hello_controller.js. This should match the following:

Make a change to app/assets/javascript/controllers/hello_controller.js.rb and see the results.

Next: Stimulus Webpacker