001. Flash messages in Rails (auto fadeOut) - cwy007/tips-and-skills GitHub Wiki

# helpers/flashes_helper.rb
module FlashesHelper
  FLASH_CLASSES = { alert: "danger", notice: "success", warning: "warning" }.freeze

  def flash_class(key)
    FLASH_CLASSES.fetch key.to_sym, key   # 用fetch 方法的第二个参数设定返回默认值
  end

  def user_facing_flashes
    flash.to_hash.slice "alert", "notice", "warning"  # slice 取出这些键并返回
  end
end
<!-- views/common/_flashes.html.erb -->
<% if flash.any? %>
  <% user_facing_flashes.each do |key, value| %>
    <div class="container-fluid">
      <div class="row justify-content-center">
        <div class="col-md-10">
          <div class="alert alert-dismissable alert-<%= flash_class(key) %> mt-1">
            <button class="close" data-dismiss="alert">&times;</button>
            <%= value %>
          </div>
        </div>
      </div>
    </div>
  <% end %>
<% end %>
<!-- views/layouts/application.html.erb -->

<%= render 'common/flashes' %>
$ ->
   flashCallback = ->
     $(".alert").fadeOut()
   setTimeout flashCallback, 6000

links: https://reinteractive.com/posts/13-ui-tips-for-flash-messages-in-rails

⚠️ **GitHub.com Fallback** ⚠️