1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails初学者】erb_lintを導入してERBファイルを整えた備忘録

Posted at

【Rails初学者向け】erb_lintを導入してERBファイルを整えた話(備忘録)

はじめに

Railsでアプリを作っていると、だんだんERBファイルがぐちゃぐちゃになってきました。
インデントがバラバラ、気づかなかった空白、空行が増えて行きました。
そんなときに知ったのがerb_lintです。
この記事は、初学者の私が erb_lint を導入して整理するまでの備忘録です。


環境

  • Ruby 3.4.2
  • Rails 8.x
  • ERBテンプレートを主に使っている構成
  • Importmap使用(Webpack未使用)

そもそもerb_lintとは

  • RuboCop のように、ERBファイルのコードスタイルを整えるツール
  • 不要な空白やインデントのズレ、タグのスペースなどを検出してくれる
  • 一部は自動修正も可能(--autocorrect

導入手順

①Gemを入れる(development限定で良い)

# Gemfile
group :development do
  gem 'erb_lint', require: false
end
bundle install

②.erb-lint.ymlを作成(※ --init は使えないことがある)

RuboCopと違って、erb_lintには--initオプションがないらしいです。
設定ファイルは手動で作ります。

# .erb-lint.yml
---
glob: "**/*.{html,text,js}{+*,}.erb"
exclude:
  - '**/vendor/**/*'
  - '**/node_modules/**/*'
linters:
  FinalNewline:
    enabled: true
  Indentation:
    enabled: true
  TrailingWhitespace:
    enabled: true
  SpaceAroundErbTag:
    enabled: true
  SelfClosingTag:
    enabled: false

ファイルは、プロジェクトのルートディレクトリ(Gemfileと同じ場所)に配置

③Lintを実行

# 全ファイルを対象にLint実行
bundle exec erb_lint --lint-all

# 自動修正も行う場合
bundle exec erb_lint --lint-all --autocorrect

ハマったポイント

  • bundle exec erblintが動かなかった
Calling `erblint` is deprecated, please call the renamed executable `erb_lint` instead.

現在はerb_lintに名前が変更されているらしく、erblintは非推奨みたいです。
正しくは以下

bundle exec erb_lint

導入してよかったこと、知ったこと

  • ERBファイルの見た目が整った
  • チームで書式を統一できるらしい
  • VSCode、GitHubPRでのレビューがスムーズになるらしい
  • 意識が向かなかった余計な行や、空白を気にしなくて良くなった
  • RuboCopだけでは守れないビューの整形がカバーできる

今後やりたいこと

  • CIで自動実行してみたい(GitHub ActionsやCircleCIに組み込む)
  • RuboCopと統一的なLint運用をしてみたい(→ rake task にまとめる)
  • .erb-lint.ymlを拡張したい

まとめ

erb_lintは、Rails初学者でも扱いやすかったです。
また、調べたところチーム開発や可読性の維持にとても役立つツールと知りました。
ただし、Rubocopとは違う点も多く、コマンド名や初期設定でつまずきやすいので注意が必要だなと感じました。
自分のコードが少しでも整うと、開発のモチベーションもぐっと上がります。
引き続き、学習を続けて行きます。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?