Skip to content

Instantly share code, notes, and snippets.

@leastbad
Created April 21, 2021 17:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leastbad/73ee3be143baa782d14a118d6fe648ba to your computer and use it in GitHub Desktop.
Save leastbad/73ee3be143baa782d14a118d6fe648ba to your computer and use it in GitHub Desktop.
CableReady + Notyf
// partial file
// you will need to `yarn add notyf`
import CableReady from 'cable_ready'
import { Notyf } from 'notyf'
import flash from '../shared/notyf'
CableReady.DOMOperations.toast = operation => {
new Notyf(flash).open(operation)
}
# partial file
class ApplicationController < ActionController::Base
include CableReady::Broadcaster
include QRCodeable
end
# config/initializers/cable_ready.rb
CableReady.configure do |config|
config.add_operation_name :toast
end
// app/javascript/shared/notyf.js
export default {
position: {
x: 'right',
y: 'top'
},
types: [
{
type: 'primary',
background: '#0d6efd',
icon: {
className: 'fas fa-check',
tagName: 'i',
color: 'white'
}
},
{ type: 'secondary', background: '#6c757d' },
{
type: 'success',
background: '#198754',
icon: {
className: 'fas fa-thumbs-up',
tagName: 'i',
color: 'white'
}
},
{
type: 'danger',
background: '#dc3545',
icon: { className: 'fas fa-times', tagName: 'i', color: 'white' }
},
{ type: 'warning', background: '#ffc107' },
{
type: 'info',
background: '#0dcaf0',
icon: {
className: 'fas fa-exclamation-triangle',
tagName: 'i',
color: 'white'
}
},
{ type: 'light', background: '#f8f9fa' },
{ type: 'dark', background: '#212529' },
{
type: 'alert',
background: '#dc3545',
icon: { className: 'fas fa-times', tagName: 'i', color: 'white' }
},
{
type: 'notice',
background: '#0d6efd',
icon: {
className: 'fas fa-check',
tagName: 'i',
color: 'white'
}
}
]
}
class ToastJob < ApplicationJob
queue_as :default
def perform(user, type, message)
cable_ready[UsersChannel].toast(type: type, message: message).broadcast_to(user)
end
end
# app/controllers/concerns/toastable.rb
# frozen_string_literal: true
module Toastable
extend ActiveSupport::Concern
included do
add_flash_types :primary, :secondary, :success, :danger, :warning, :info, :light, :dark
after_action :broadcast_flash, if: :user_signed_in?
after_action :clear_flash, unless: :user_signed_in?
private
def broadcast_flash
flash.each { |k, v| ToastJob.set(wait: 2.second).perform_later(current_user, k, v) }
flash.clear
end
def clear_flash
flash.clear
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment