Skip to content

Instantly share code, notes, and snippets.

@jamgar
Last active July 11, 2022 22:47
Show Gist options
  • Save jamgar/a4f1378fce74e9fd85029550730030e1 to your computer and use it in GitHub Desktop.
Save jamgar/a4f1378fce74e9fd85029550730030e1 to your computer and use it in GitHub Desktop.
Dismiss Flash Messages with Turbo
# app/views/shared/_flash_messages.html.erb
<% flash.each do |name, msg| %>
<div class="flex justify-between p-4 mb-4 bg-blue-100 border-t-4 border-blue-500 dark:bg-blue-200" role="alert">
<div class="flex">
<svg class="flex-shrink-0 w-5 h-5 text-blue-700" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"></path></svg>
<div class="ml-3 text-sm font-medium text-blue-700">
<%= msg %>
</div>
</div>
# This is the Dismiss button
<%= button_to flash_path, class: " -mx-1.5 -my-1.5 bg-blue-100 dark:bg-blue-200 text-blue-500 rounded-lg focus:ring-2 focus:ring-blue-400 p-1.5 hover:bg-blue-200 dark:hover:bg-blue-300 inline-flex h-8 w-8" do %>
<span class="sr-only">Dismiss</span>
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg>
<% end %>
# End of button
</div>
<% end %>
# app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Flashapp</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag "tailwind", "inter-font", "data-turbo-track": "reload" %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
</head>
<body>
<main class="container mx-auto mt-28 px-5">
<!-- ADD THESE LINES -->
<div id="flash-messages">
<%= render "shared/flash_messages" %>
</div>
<!-- END OF LINES -->
<%= yield %>
</main>
</body>
</html>
# app/views/flash/dismiss.turbo_stream.erb
<%= turbo_stream.update "flash-messages", partial: "shared/flash_messages" %>
# app/controllers/flash_controller.rb
class FlashController < ApplicationController
def dismiss
flash.clear
end
end
# config/routes.rb
Rails.application.routes.draw do
post 'flash', to: 'flash#dismiss'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment