Open9

Ruby(Rails)勉強メモ

Dev-kentaDev-kenta

Ruby(Rails)のスマートな書き方

https://qiita.com/jnchito/items/dedb3b889ab226933ccf
https://blog.recruit.co.jp/rmp/server-side/rails-development-policy/

String#squish

https://qiita.com/QUANON/items/42c6ee05d43108388b42

is_a?とinstance_of?どっち使ってクラスの判定すればいいか?

基本的にはis_a?でチェックするのが良さそう。
https://qiita.com/akihiro_kubota/items/3ca17fe7f7bd810e4cf9

transform_values

https://qiita.com/ayacai115/items/61e4bfed2171747cc6dd#hashtransform_valuesruby-24

i18nでhtmlを使う

キー名の最後に_htmlを使うと良い。
html_safeを使うよりセキュリティ的に安全。
https://qiita.com/tnj/items/c9e893124c1b000b5355

メモ化するとき

@main_address ||= begin
  maybe_main_address = home_address if prefers_home_address?
  maybe_main_address = work_address unless maybe_main_address
  maybe_main_address = addresses.first unless maybe_main_address
end

begin-endで囲ったブロックをまとめることができる?

https://www.justinweiss.com/articles/4-simple-memoization-patterns-in-ruby-and-one-gem/

配列に含まれるnilを除去

compact_blankを使う。
https://qiita.com/SoarTec-lab/items/0c19a4eb5e17c417d165

ActiveRecord::Relationexcluding

where.notのショートハンド
以下のようなSQLが発行される。

Post.excluding(post)
# SELECT "posts".* FROM "posts" WHERE "posts"."id" != 1

https://techracho.bpsinc.jp/hachi8833/2021_02_22/104118

sendメソッド

メソッドを動的に呼び出せる。
またRspecでprivateメソッド呼び出しにも使える。
https://qiita.com/hogucc/items/79da134520ee731fe298

tryメソッド

オブジェクトがnilで無い場合のみ、そのオブジェクトのメソッドを実行できる。
https://qiita.com/ngron/items/ec5f72639634949c126e
https://railsdoc.com/page/try

大量のデータを扱うときに気をつけること

取得するとき

find_eachfind_in_batchesを使う

insertやupdateするとき

バルクインサートやupdate_all を使う
https://techblog.lclco.com/entry/2019/07/31/180000

論理削除が実装されているmodelで物理削除する

really_destroyを使用すると物理削除される。
https://codeclub965.com/?p=1475

論理削除されてるレコードも検索する

with_deleted を使用する
https://qiita.com/opiyo_taku/items/30dc2eafd56b4e13d213

文字列の範囲指定

僕の名前はテスト太郎ですという文字列があった場合。

name = "僕の名前はテスト太郎です"
name[0...4] => 僕の名前
name[5...10] => テスト太郎

こんな感じで範囲指定できる。
https://docs.ruby-lang.org/ja/2.7.0/method/String/i/slice.html

cloneとdupの違い

clone => 既存レコード、id同じ、リレーション維持
dup => 新規レコード、idがnil、リレーション外れる
https://mgre.co.jp/blog/3327

thenの使いどころ

https://nishinatoshiharu.com/ruby-then-overview/