最近rails書いてて気づいたこと

railsのEnumerableの拡張が便利

https://guides.rubyonrails.org/active_support_core_extensions.html#extensions-to-enumerable

ActiveRecordのpluckみたいな処理を、hashが要素になっている配列に対して行おうとした時に見つけました。

こういうのは、普通mapでやると思いますが、pluckで書くと若干シンプルになります。

require 'active_support/all'

sample = [{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }]
mapped = sample.map { |e| e[:name] }
plucked = sample.pluck(:name) # => ["David", "Rafael", "Aaron"]
p mapped == plucked # true
# 上記2つは同じ結果

sample2 = [{ id: 1, name: "David" }, { id: 2, name: "Rafael" }]
p sample2.map { |e| [e[:id], e[:name]] }
p sample2.pluck(:id, :name) # => [[1, "David"], [2, "Rafael"]]
# 上記2つも同じ結果

vscodeのrubocopのプラグインが、GitHub Copilot並みに便利

というか、rubocopが便利というか、Copilotが何と言おうが、プロジェクトの決まり上、rubocopが正ということになったりもします。

最近の自分のプロジェクトでは、rubocop-railsまで入れてますが、

https://docs.rubocop.org/rubocop-rails/cops_rails.html#railsuniquevalidationwithoutindex

は、db/schema.rb の中身までチェックして、指摘してくれてるらしいです。

それと下記の2つは、こんなメソッド知らなかったみたいなものも教えてくれます

https://docs.rubocop.org/rubocop/cops_style.html#styleeachwithobject

https://docs.rubocop.org/rubocop/cops_style.html#stylefileread

ということで最近はrails書くときは、Copilotは無効化してます。