LoginSignup
4
6

More than 5 years have passed since last update.

Bootstrapを使う際のRailsでのフラッシュの仕組み

Last updated at Posted at 2018-12-07

初めに

「Ruby on Rails tutorial」 や 「Ruby on Rails 5 の上手な使い方」にのっていたflashメッセージの表示するシステムを忘れないように書きます。

flashについて

flash.rb
flash[:notice] = "フラッシュです"
redirect_to path

見たいな感じで使います。

bootstrapのカラーについて

bootstrapでは
alert alert-*** 
みたいなクラスを設定することでいい感じでデザインしてくれます。
al.png

こんな感じです

いろんな色が用意されていて

alert-success
alert-danger
alert-info
alert-warning

があります。

この四種類のalertを別々に書いてやろうとすると…

flash-all.rb
if flash[:notice]
  <div class="alert alert-notice">
    <%= flash[:notice] %>
  </div>
elsif flash[:info]
  <div class="alert alert-info">
    <%= flash[:info] %>
  </div>
elsif flash[:danger]
  <div class="alert alert-danger">
    <%= flash[:danger] %>
  </div>
elsif flash[:warning]
  <div class="alert alert-danger">
    <%= flash[:danger] %>
  </div>
end

と結構長くなってしまいます。

application_helper.rbにヘルパーメソッドを書く

この長いのをどうにかするためにapplication_helper.rbに

application_helper.rb

def flash_message(message, klass)
  content_tag(:div, class: "alert alert-#{klass}") do
    concat content_tag(:button, 'x', class: 'close', data: {dismiss: 'alert'})
    concat raw(message)
  end
end


application.html.erbでさっきのメソッドを使う

application.html.erb

<%= flash_message(flash[:success], :success) if flash[:success] %>
<%= flash_message(flash[:error], :danger) if flash[:error] %>
<%= flash_message(flash[:alert], :warning) if flash[:alert] %>
<%= flash_message(flash[:notice], :info) if flash[:notice] %>

こうすれば解決です。

ちょっとすっきりしました。

何か間違いがあればご指摘いただければと思います。

参考文献
「Ruby on Rails5 の上手な使い方」
https://www.amazon.co.jp/Rails-5の上手な使い方-現場のエンジニアが教えるRailsアプリケーション開発の実践手法-Engineers-Books/dp/4798153095/ref=sr_1_4?ie=UTF8&qid=1544168971&sr=8-4&keywords=ruby+on+rails+5

4
6
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
4
6