LoginSignup
8
13

More than 3 years have passed since last update.

【Rails】プロジェクトを作ったら追加したい設定やgemファイル

Last updated at Posted at 2019-01-04

Rails初心者である自分用のメモとして置いておきます。随時更新します。
バージョン:Ruby2.5.3, Rails 5.2.2

基本的なこと

  • gemはGemfileに記述する(特に指定がなければgroupの外側に記述)
  • バージョンを指定する場合、RubyGems.orgでチェックする
  • gemを追加した後は、ターミナルで$ bundle install
  • config内を変更した後は、rails serverを再起動

日本語化

タイムゾーンの設定

プロジェクト内で扱う日時を日本標準時に合わせる場合、この設定は必須です。

config/application.rb
class Application < Rails::Application
  config.time_zone = 'Tokyo'
  config.active_record.default_timezone = :local
  # この二行の記述を追加
end

エラーメッセージの日本語化(i18n)

  • gem 'rails-i18n'
  • config/locales/ja.ymlを作成し、ja.ymlをコピペ
config/application.rb
class Application < Rails::Application
  config.i18n.default_locale = :ja # この記述を追加
end

日時の日本語化

  • config/initializers/time_formats.rbを作成し、フォーマットを追加
initializers/time_formats.rb
Time::DATE_FORMATS[:datetime_jp] = '%Y年%m月%d日 %H時%M分'
# :datetime_jpは別の名前でも可
  • viewでは以下のように記述
index.html.erb
<%= article.created_at.to_s(:datetime_jp) %>

便利なgemファイル

cssフレームワーク(bootstrap)

  • gem 'bootstrap'
  • stylesheets/application.cssを.scssに変更
  • stylesheets/application.scssに@import "bootstrap";の記述を追加

ページネイト(kaminari)

  • gem 'kaminari'
terminal
$ rails g kaminari:config # 設定の変更
$ rails g kaminari:views default # 見た目の変更

viewをシンプルに記述する(slim)

slim

Slim は 不可解にならない程度に view の構文を本質的な部品まで減らすことを目指したテンプレート言語です。標準的な HTML テンプレートからどれだけのものを減らせるか、検証するところから始まりました。(<, >, 閉じタグなど) 多くの人が Slim に興味を持ったことで, 機能的で柔軟な構文に成長しました。

  • gem 'slim-rails'
config/application.rb
class Application < Rails::Application
  config.generators.template_engine = :slim # この記述を追加
end

erbからslimへの変換

  • gem 'html2slim'
terminal
$ gem install slim
$ bundle exec erb2slim app/views/ --delete # 既存のerbファイルのslimを作成し、erbを削除する

development, test用のgem

group :development, :test do内に記述

SQLを整然と表示する(flog)

  • gem 'rails-flog', require: 'flog'

before
 ↓
after

development用のgem

group :development do内に記述

スキーマ情報をmodel.rbに記述する(annotate)

  • gem 'annotate'
$ bundle exec annotate # テーブルのカラム情報が記述される
$ bundle exec annotate --routes # ルート情報が記述される
  # annotate --routes でも可
$ rails g annotate:install
      create  lib/tasks/auto_annotate_models.rake

auto_annotate_models.rake内の記述を変更すると設定を変更できる。

lib/tasks/auto_annotate_models.rake
      .
      .
      'skip_on_db_migrate'        => 'true',
      # db:migrateするたびに勝手に更新されない。

参考資料

8
13
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
8
13