Lucky - StimulusJS

Install StimulusJS in a Lucky Application
Used 46 times
Created by
S Stephen Dolan

Usage

From within a Lucky application with the bloat gem installed, run:
bloat with https://railsbytes.com/script/zl0sKQ

Run this command in your Rails app directory in the terminal:

rails app:template LOCATION="https://railsbytes.com/script/zl0sKQ"

Template Source

Review the code before running this template on your machine.

def build_sample_controller(js_extension)
  if js_extension == "ts"
      create_file "src/js/controllers/hello_controller.ts" do<<~EOF
      import { Controller } from "stimulus";

      export default class extends Controller {
        // Defines a `this.helloTarget` that you can use in your functions.
        static get targets(): Array<string> {
          return ["hello"];
        }

        // Called whenever the controller is attached to an element on the page.
        initialize(): void {
          console.log("Hello! StimulusJS is working!");
        }

        // Can be called from within this file with `this.hello()`, or in an action in your HTML.
        hello(): void {
          console.log("Hello! You're in a StimulusJS function!");
        }
      }
      EOF
    end
  else
    create_file "src/js/controllers/hello_controller.js" do<<~EOF
      import { Controller } from "stimulus";

      export default class extends Controller {
        // Defines a `this.helloTarget` that you can use in your functions.
        static get targets() {
          return ["hello"];
        }

        // Called whenever the controller is attached to an element on the page.
        initialize() {
          console.log("Hello! StimulusJS is working!");
        }

        // Can be called from within this file with `this.hello()`, or in an action in your HTML.
        hello() {
          console.log("Hello! You're in a StimulusJS function!");
        }
      }
      EOF
    end
  end
end

def yarn(*packages)
  run("yarn add #{packages.join(" ")}")
end

js_extension = "js"

if yes? "Are you using TypeScript? [y/N]"
  js_extension = "ts"
end

# Add StimulusJS to package.json
yarn "stimulus"

append_to_file "src/js/app.#{js_extension}" do<<~EOF
  import { Application } from "stimulus";
  import { definitionsFromContext } from "stimulus/webpack-helpers";

  const application = Application.start();
  const context = require.context("./controllers", true, /\.#{js_extension}$/);
  application.load(definitionsFromContext(context));
  EOF
end

if yes?("Would you like to add a sample StimulusJS controller to verify things are working? [y/N]")
  build_sample_controller(js_extension)
end
Mark
© 2020 GoRails, LLC