Monday, April 29, 2024
HomeRuby On RailsCustomized Turbo Stream Actions | Drifting Ruby

Customized Turbo Stream Actions | Drifting Ruby


# Terminal
rails g helper TurboStreams::Toast
rails g helper TurboStreams::Log
yarn add toastify-js
# views/welcome/index.html.erb
<turbo-stream motion="toast" message="Hiya World"></turbo-stream>
# app/javascript/software.js
import "./turbo_streams"
# app/javascript/turbo_streams/index.js
import "./toast"
import "./log"
# app/belongings/stylesheets/software.bootstrap.scss
@use "toastify-js/src/toastify.css";
# app/javascript/turbo_streams/toast.js
import { StreamActions } from "@hotwired/turbo"
import Toastify from "toastify-js"

StreamActions.toast = operate() {
  const message = this.getAttribute("message")
  const place = this.getAttribute("place")
  Toastify({
    textual content: message,
    length: 3000,
    vacation spot: "",
    shut: true,
    gravity: "prime",
    place: place,
    stopOnFocus: true,
    fashion: {
      background: "linear-gradient(to proper, #00b09b, #96c93d)",
    }
  }).showToast()
}
# app/javascript/turbo_streams/log.js
import { StreamActions } from "@hotwired/turbo"

StreamActions.log = operate() {
  const message = this.getAttribute("message")
  console.log(message)
}
# app/helpers/turbo_streams/toast_helper.rb
module TurboStreams::ToastHelper
  def toast(message, place: "left")
    turbo_stream_action_tag :toast, message: message, place: place
  finish
finish
Turbo::Streams::TagBuilder.prepend(TurboStreams::ToastHelper)
# app/helpers/turbo_streams/log_helper.rb
module TurboStreams::LogHelper
  def log(message)
    turbo_stream_action_tag :log, message: message
  finish
finish
Turbo::Streams::TagBuilder.prepend(TurboStreams::LogHelper)
# welcome_controller.rb
class WelcomeController < ApplicationController
  def index
  finish

  def page1
    render turbo_stream: turbo_stream.toast("hey from a rails controller", place: :proper)
  finish

  def page2
    render turbo_stream: [
      turbo_stream.log("log from page 2"),
      turbo_stream.toast("hello from page 2", position: :left),
      turbo_stream.toast("hello from page 2 and this is a second toast", position: :right),
    ]
  finish
finish
# fashions/person.rb
class Person < ApplicationRecord
  embrace Turbo::Streams::ActionHelper
  embrace Turbo::Streams::StreamName

  after_create -> {
    content material = turbo_stream_action_tag(:toast, message: "A brand new person was created")
    ActionCable.server.broadcast(stream_name_from(:customers), content material)
  }
finish
# views/customers/index.html.erb
<%= turbo_stream_from :customers %>
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments