学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

【学習5.0】【MacOSX】フラッシュメッセージ(toastr)

フラッシュメッセージを「torstr」にして日本語化していきます。


記述追加 Gemfile (65行目)

# toastr
gem 'toastr-rails', '~> 1.0'

# 日本語化
gem 'rails-i18n'



Gemfile

source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.7', '>= 5.0.7.1'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

# bulma
gem 'bulma-rails', '~> 0.7.4'
gem 'bulma-extensions-rails', '~> 1.0.30'

# デバイス
gem 'devise', '~>4.2'

# アバター
gem 'gravtastic'

# toastr
gem 'toastr-rails', '~> 1.0'

# 日本語化
gem 'rails-i18n'



コマンド
bundle


記述追加 app\assets\javascripts\application.js (15行目)

//= require toastr



app\assets\javascripts\application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require toastr
//= require gravtastic
//= require turbolinks
//= require_tree .



記述追加 app\assets\stylesheets\application.scss(20行目)

@import "toastr";



app\assets\stylesheets\application.scss

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */
 
 @import 'bulma';
 @import 'bulma-extensions';
 
 @import "toastr";

 $spaceamounts: (0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100);
 $sides: (top, bottom, left, right);
 @each $space in $spaceamounts {
   @each $side in $sides {
     .m-#{str-slice($side, 0, 1)}-#{$space} {
       margin-#{$side}: #{$space}px !important;
     }
     .p-#{str-slice($side, 0, 1)}-#{$space} {
       padding-#{$side}: #{$space}px !important;
     }
   }
   .m-#{$space} {
     margin: #{$space}px !important;
   }
   .p-#{$space} {
     padding: #{$space}px !important;
   }
   .h-#{$space} {
     margin-top: #{$space}px !important;
     margin-bottom: #{$space}px !important;
   }
   .f-#{$space} {
     font-size: #{$space}px !important;
   }
 }
 .is-horizontal-center {
   justify-content: center;
 }
 .small-title {
   font-size: 10px;
 }


 //ホームページ用
 .has-bg-img {
   background: url('/assets/home/background01.jpg') center center;
   background-size: cover;
 }

 //ナビバーのアバター画像位置
 .image {
   //margin-top: 0.6rem;
   display: flex; /* flexに */
   align-items: center;
 }

 
 // googlフォント用
 .title {
   font-family: 'Kosugi Maru', "Helvetica Neue", "Helvetica", "Arial", sans-serif;
 }
 .button {
   font-family: 'Kosugi Maru', "Helvetica Neue", "Helvetica", "Arial", sans-serif;
 }
 .field {
   font-family: 'Kosugi Maru', "Helvetica Neue", "Helvetica", "Arial", sans-serif;
 }
 .all {
   font-family: 'Kosugi Maru', "Helvetica Neue", "Helvetica", "Arial", sans-serif;
 }
 .navbar-item {
   font-family: 'Kosugi Maru', "Helvetica Neue", "Helvetica", "Arial", sans-serif;
 }
 .input {
   font-family: 'Kosugi Maru', "Helvetica Neue", "Helvetica", "Arial", sans-serif;
 }
 .card-content {
   font-family: 'Kosugi Maru', "Helvetica Neue", "Helvetica", "Arial", sans-serif;
 }
 .section {
   font-family: 'Kosugi Maru', "Helvetica Neue", "Helvetica", "Arial", sans-serif;
 }
 .card-header-title is-centered {
   font-family: 'Kosugi Maru', "Helvetica Neue", "Helvetica", "Arial", sans-serif;
 }
 .modal-card-title {
   font-family: 'Kosugi Maru', "Helvetica Neue", "Helvetica", "Arial", sans-serif;
 }
 

  



「app\views\shared」フォルダに「_message.html.erb」ファイルを新規作成


app\views\shared\_message.html.erb (新規作成したファイル)

<% unless flash.empty? %>
  <script type="text/javascript">
    <% flash.each do |key, value| %>
      <% type = key.to_s.gsub('alert','error').gsub('notice','success') %>
      toastr['<%= type %>']('<%= value %>')
    <% end %>
  </script>
<% end %>



「app\views\layouts\application.html.erb」ファイルの15,16行目の記述を削除し、そこに「<%= render 'shared/message' %>」の記述を追加します。


記述削除 app\views\layouts\application.html.erb(15,16行目)

    <p class="notice"><%= notice %></p>
    <p class="alert"><%= alert %></p>



記述追加 app\views\layouts\application.html.erb(15行目)

<%= render 'shared/message' %>



app\views\layouts\application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Gakushuu</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
  
    <%= render  "shared/navbar" %>

    <%= render 'shared/message' %>

    <%= yield %>
  </body>
</html>



メッセージの日本語化設定をします。


「config\locales」フォルダに「devise.ja.yml」ファイルを新規作成します。


config\locales\devise.ja.yml(新規作成したファイル)

# Additional translations at https://github.com/plataformatec/devise/wiki/I18n

ja:
  devise:
    confirmations:
      confirmed: 'アカウントを登録しました。'
      send_instructions: 'アカウントの有効化について数分以内にメールでご連絡します。'
      send_paranoid_instructions: "あなたのメールアドレスが登録済みの場合、本人確認用のメールが数分以内に送信されます。"
    failure:
      already_authenticated: 'すでにログインしています。'
      inactive: 'アカウントが有効化されていません。メールに記載された手順にしたがって、アカウントを有効化してください。'
      invalid: "%{authentication_keys} もしくはパスワードが不正です。"
      locked: 'あなたのアカウントは凍結されています。'
      last_attempt: 'あなたのアカウントが凍結される前に、複数回の操作がおこなわれています。'
      not_found_in_database: "%{authentication_keys} もしくはパスワードが不正です。"
      timeout: 'セッションがタイムアウトしました。もう一度ログインしてください。'
      unauthenticated: 'アカウント登録もしくはログインしてください。'
      unconfirmed: 'メールアドレスの本人確認が必要です。'
    mailer:
      confirmation_instructions:
        subject: 'アカウントの有効化について'
      reset_password_instructions:
        subject: 'パスワードの再設定について'
      unlock_instructions:
        subject: 'アカウントの凍結解除について'
      password_change:
        subject: 'パスワードの変更について'
    omniauth_callbacks:
      failure: "%{kind} アカウントによる認証に失敗しました。理由:(%{reason})"
      success: "%{kind} アカウントによる認証に成功しました。"
    passwords:
      no_token: "このページにはアクセスできません。パスワード再設定メールのリンクからアクセスされた場合には、URL をご確認ください。"
      send_instructions: 'パスワードの再設定について数分以内にメールでご連絡いたします。'
      send_paranoid_instructions: "あなたのメールアドレスが登録済みの場合、パスワード再設定用のメールが数分以内に送信されます。"
      updated: 'パスワードが正しく変更されました。'
      updated_not_active: 'パスワードが正しく変更されました。'
    registrations:
      destroyed: 'アカウントを削除しました。またのご利用をお待ちしております。'
      signed_up: 'アカウント登録が完了しました。'
      signed_up_but_inactive: 'ログインするためには、アカウントを有効化してください。'
      signed_up_but_locked: 'アカウントが凍結されているためログインできません。'
      signed_up_but_unconfirmed: '本人確認用のメールを送信しました。メール内のリンクからアカウントを有効化させてください。'
      update_needs_confirmation: 'アカウント情報を変更しました。変更されたメールアドレスの本人確認のため、本人確認用メールより確認処理をおこなってください。'
      updated: 'アカウント情報を変更しました。'
    sessions:
      signed_in: 'ログインしました。'
      signed_out: 'ログアウトしました。'
      already_signed_out: '既にログアウト済みです。'
    unlocks:
      send_instructions: 'アカウントの凍結解除方法を数分以内にメールでご連絡します。'
      send_paranoid_instructions: 'アカウントが見つかった場合、アカウントの凍結解除方法を数分以内にメールでご連絡します。'
      unlocked: 'アカウントを凍結解除しました。'
  errors:
    messages:
      already_confirmed: 'は既に登録済みです。ログインしてください。'
      confirmation_period_expired: "の期限が切れました。%{period} までに確認する必要があります。 新しくリクエストしてください。"
      expired: 'の有効期限が切れました。新しくリクエストしてください。'
      not_found: 'は見つかりませんでした。'
      not_locked: 'は凍結されていません。'
      not_saved:
        one: "エラーが発生したため %{resource} は保存されませんでした:"
        other: "%{count} 件のエラーが発生したため %{resource} は保存されませんでした:"



同じく「config\locales」フォルダに「ja.yml」ファイルを新規作成


config\locales\ja.yml(新規作成したファイル)

ja:
  activerecord:
    attributes:
      user:
        full_name: 氏名
        current_password: パスワード
        password: パスワード
        email: メールアドレス

  time:
    formats:
        full_date: "%Y年%m月%d日 (%a)"
        



記述追加 config\application.rb(16,19行目)

    #日本語化
    config.i18n.default_locale = :ja

    # 日本時間に変更
    config.time_zone = 'Tokyo'



config\application.rb

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module Gakushuu
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    #日本語化
    config.i18n.default_locale = :ja

    # 日本時間に変更
    config.time_zone = 'Tokyo'

  end
end



「views\shared」フォルダに「_devisemes.html.erb」ファイルを新規作成


app\views\shared\_devisemes.html.erb(新規作成したファイル)

<% unless resource.errors.empty? %>
  <script type="text/javascript">
    <% resource.errors.full_messages.each do |value| %>
      toastr.error('<%= value %>')
    <% end %>
  </script>
<% end %>



以下の4つのファイルに記述の削除と記述追加。

  1. app\views\devise\registrations\new.html.erb
  2. app\views\devise\registrations\edit.html.erb
  3. app\views\devise\passwords\new.html.erb
  4. app\views\devise\passwords\edit.html.erb



削除する記述

<%= render "devise/shared/error_messages", resource: resource %>



追加する記述

<%= render 'shared/devisemes' %>





1. app\views\devise\registrations\new.html.erb(12行目)

<section class="hero is-light is-fullheight">
  <div class="hero-body">
    <div class="container">
      <div class="columns is-centered">
        <div class="column is-6-table is-6-desktop is-6-widescreen">
          <div class="box">
            
            <div class="field has-text-centered">
              <strong>新規ユーザ登録</strong>
            </div>
            <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
              <%= render 'shared/devisemes' %>
              <div class="field">
                <%= f.label :氏名, class: "label" %>
                <%= f.text_field :full_name, autofocus: true, autocomplete: "full_name", class: "input" %>
              </div>
              <div class="field">
                <%= f.label :メールアドレス, class: "label" %>
                <%= f.email_field :email, autofocus: true, autocomplete: "email", class: "input" %>
              </div>
              <div class="field">
                <%= f.label :パスワード, class: "label" %>
                <% if @minimum_password_length %>
                <em>(<%= @minimum_password_length %> 文字以上)</em>
                <% end %><br />
                <%= f.password_field :password, autocomplete: "new-password", class: "input" %>
              </div>
              <div class="field">
                <%= f.label :確認, class: "label" %>
                <%= f.password_field :password_confirmation, autocomplete: "new-password", class: "input" %>
              </div>
              <div class="field">
                <%= f.submit "登録する", class: "button is-danger is-fullwidth m-t-10 m-b-10" %>
              </div>
            <% end %>
            <%= render "devise/shared/links" %>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>



2. app\views\devise\registrations\edit.html.erb(12行目)

<section class="hero is-light is-fullheight">
  <div class="hero-body">
    <div class="container">
      <div class="columns is-centered">
        <div class="column is-6-table is-6-desktop is-6-widescreen">
          <div class="box">
            
            <div class="field has-text-centered">
              <strong>ユーザ登録情報編集</strong>
            </div>
            <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
              <%= render 'shared/devisemes' %>
              <div class="field">
                <%= f.label :氏名, class: "label" %>
                <%= f.text_field :full_name, autofocus: true, autocomplete: "full_name", class: "input" %>
              </div>
              <div class="field">
                <%= f.label :メールアドレス, class: "label" %>
                <%= f.email_field :email, autofocus: true, autocomplete: "email", class: "input" %>
              </div>
              <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
                <div>現在、確認を待っています: <%= resource.unconfirmed_email %></div>
              <% end %>
              <div class="field">
                <%= f.label :パスワード, class: "label"  %> <i>(変更しない場合は空白のままにします)</i>
                <%= f.password_field :password, autocomplete: "new-password", class: "input" %>
                <% if @minimum_password_length %>
                  <br />
                  <em><%= @minimum_password_length %> 文字以上</em>
                <% end %>
              </div>
              <div class="field">
                <%= f.label :確認, class: "label"  %>
                <%= f.password_field :password_confirmation, autocomplete: "new-password", class: "input" %>
              </div>
              <div class="field">
                <%= f.label :現在のパスワード, class: "label"  %> <i>(変更するには現在のパスワードが必要です)</i><br />
                <%= f.password_field :current_password, autocomplete: "current-password", class: "input" %>
              </div>
              <div class="field">
                <%= f.submit "更新する", class: "button is-danger is-fullwidth" %>
              </div>
            <% end %>
            <%= link_to "戻る", :back, class: "button is-fullwidth m-t-10" %>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>



3. app\views\devise\passwords\new.html.erb(12行目)

<section class="hero is-light is-fullheight">
  <div class="hero-body">
    <div class="container">
      <div class="columns is-centered">
        <div class="column is-6-table is-6-desktop is-6-widescreen">
          <div class="box">
            <div class="field has-text-centered">
              <strong>パスワードをお忘れですか?</strong>
            </div>
            <br/>
            <%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %>
              <%= render 'shared/devisemes' %>
              <div class="field">
                <%= f.label :メールアドレス, class: "label" %>
                <%= f.email_field :email, autofocus: true, autocomplete: "email", placeholder: "メールアドレスを入力してください", class: "input" %>
              </div>
              <br/>
              <div class="actions">
                <%= f.submit "パスワード再設定メールを送る", class: "button is-danger is-fullwidth m-t-10 m-b-10" %>
              </div>
            <% end %>
            <br/>
            <p>メールに記載されているリンクをクリックするとパスワードの再設定ができます。</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>



4. app\views\devise\passwords\edit.html.erb(15行目)

<section class="hero is-light is-fullheight">
  <div class="hero-body">
    <div class="container">
      <div class="columns is-centered">
        <div class="column is-6-table is-6-desktop is-6-widescreen">
          <div class="box">

            <div class="field has-text-centered">
              <strong>パスワードを変更します</strong>
            </div>
            <br/>


            <%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %>
              <%= render 'shared/devisemes' %>
              <%= f.hidden_field :reset_password_token %>

              <div class="field">

                <% if @minimum_password_length %>
                  <em>新しいパスワード(<%= @minimum_password_length %> 文字以上)</em><br />
                <% end %>
                <%= f.password_field :password, autofocus: true, autocomplete: "new-password", placeholder: "新しいパスワードを入力して下さい", class: "input" %>
              </div>
              <br/>
              <div class="field">
                <%= f.password_field :password_confirmation, autocomplete: "new-password", placeholder: "確認", class: "input" %>
              </div>
              <br/>
              <div class="actions">
                <%= f.submit "パスワードを変更する", class: "button is-danger is-fullwidth m-t-10 m-b-10" %>
              </div>
            <% end %>


          </div>
        </div>
      </div>
    </div>
  </div>
</section>



ブラウザ確認
http://localhost:3000/

フラッシュメッセージ
フラッシュメッセージ