deviseの導入について

インフラの勉強と並行して、現在は自分だけで使用している業務効率化アプリを職場の人も使えるように改善をしようと思う。

仕様については割愛するが、ユーザー毎に管理したい情報がありユーザ登録が必要になるので、deviseを使用して導入する。

 

deviseの使用方法

1gem 'devise'をbundle install
2.bundle exec rails g devise:install
これで設定を記述するconfig/initializers/devese.rbと言語設定のlocalesファイルがインストールされる。

以下が出力される。

===============================================================================

Some setup you must do manually if you haven't yet:

1. Ensure you have defined default url options in your environments files. Here
is an example of default_url_options appropriate for a development environment
in config/environments/development.rb:

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

In production, :host should be set to the actual host of your application.

2. Ensure you have defined root_url to *something* in your config/routes.rb.
For example:

root to: "home#index"

3. Ensure you have flash messages in app/views/layouts/application.html.erb.
For example:

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

4. You can copy Devise views (for customization) to your app by running:

rails g devise:views

===============================================================================

 

今回userモデルを作成する目的はuser毎に情報を管理することなので、メーラーやパスワード再設定は導入しない。
ということで、ここからやることは、rootingの設定とflashの設定、modelを作成、viewを作成する。

3.bundle exec rails g devise user

これでroutesの設定とモデル、migration fileが作成される。
作成されたmigrationファイルから必要なもののコメントを外し、rails db:migrateする。

 

4bundle exec rails g devise:views

これでdeviseのviewファイルを一括コピーする.

5viewをslim変換し、日本語化対応する

gem 'devise-i18n'
gem 'devise-i18n-views'
gem 'devise-bootstrap-views'

以上のgemをbundleする。

bundle exec rails generate devise:views:bootstrap_templates

コマンドを叩きviewをbootstrap対応させる。

for file in app/views/devise/**/*.erb; do erb2slim $file ${file%erb}slim && rm $file; done

コマンドを叩き、erbファイルを、slim変換し重複を除去する。

 

次に日本語化対応をする。
$ rails generate devise:views:locale ja
でconfig/localesにdevice.views.ja.ymlが作成される。

その後、config/application.rbに

config.i18n.default_locale = :ja

を追記し、サーバー再起動後、確認すると日本語化されている。
しかし完全な日本語化はされないので、devise専用のjaファイルだけでなくアプリ全体に使用できるファイルを入れておく。

curl -s https://raw.githubusercontent.com/svenfuchs/rails-i18n/master/rails/locale/ja.yml -o config/locales/ja.yml

これでconfig/locales/ja.ymlがインストールされる。

 

ざっくりこんな感じで日本語化対応でlogin機能が作れるんでは?と思う。

 

rubymineショートカット
command+f ファイル内検索

参考:

github.com

 

qiita.com

suin.io

morizyun.github.io