LoginSignup
3
1

More than 3 years have passed since last update.

【Rails】Semantic UIを使って動的にフラッシュメッセージを表示する方法

Last updated at Posted at 2020-08-24

Semantic UI

BootstrapのフレームワークであるSemantic UIを使って、Railsに動的なフラッシュメッセージを導入する方法を以下に記しておきます。

Railsを使ったSemantic UIの導入方法は、以下の記事を参考にしてみてください。

class属性を動的に設定するためのヘルパーを作成

app/helpers/application_helper.rb
module ApplicationHelper
  def flash_class(level)
    case level
    when "success" then "ui success message"
    when "danger" then "ui error message"
    end
  end
end

フラッシュメッセージ用のパーシャルを作成

上記で作ったflash_class(level)メソッドを使用。

app/views/shared/_flash_message.html.slim
- flash.each do |message_type, message|
  div class="#{flash_class(message_type)} closable"
    i class="close icon"
    = message

JavaScriptの導入

フラッシュメッセージの右上の×ボタンを押すと、フラッシュメッセージが消えるようにjsの記述をしておく。

app/javascript/packs/flash_message.js
$(function () {
  $(".closable .close.icon").on("click", () => {
    $('.closable').fadeOut("slow");
  });
});

エントリポイントであるapp/javascript/packs/application.jsに、app/javascript/packs/flash_message.jsを読み込んでおく。

app/javascript/packs/application.js
require("packs/flash_message")

パーシャルをレンダリングする。

== render "shared/flash_message"でオッケーですね。

app/views/layouts/application.html.slim
doctype html
html
  head
    title
      = page_title(yield(:title))
    = csrf_meta_tags
    = csp_meta_tag
    = stylesheet_pack_tag "application", media: "all", "data-turbolinks-track": "reload"
    = javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'
  body
    == render 'shared/header'

    == render "shared/flash_message"

    == yield

    == render 'shared/footer'

add_flash_typesを記述

Bootstrapに用意されているスタイルのフラッシュを定義。
この記述によって、毎回flash: { success: 'ログインに成功しました' }と書かなくて済むようになる。

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  add_flash_types :success, :info, :warning, :danger
end

各コントローラで、flash_class(level)メソッドに渡すキーとバリューをセットする。

app/controllers/user_sessions_controller.rb
class UserSessionsController < ApplicationController
  skip_before_action :require_login, only: %i[new create]

  def new; end

  def create
    @user = login(params[:email], params[:password])
    if @user
      redirect_back_or_to root_path, success: 'ログインに成功しました'
    else
      flash.now[:danger] = 'ログインに失敗しました'
      render action: 'new'
    end
  end

ブラウザで確認

記述は以上です。
最後にブラウザで挙動を確認します!レイアウトは気にしないでください🙄

  • ログイン成功時
    スクリーンショット 2020-08-24 16.57.06.png

  • ログイン失敗時
    スクリーンショット 2020-08-24 16.49.22.png

  • ×ボタンを押すとフラッシュメッセージが消える。
    Image from Gyazo

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1