投稿日:2026/10/1
更新日:2026/10/1

Rails のコードに出てくる @current_user や @now ||= Time.current が何をしているのか、
「複数生成できる」という理解で止まっていたので、Ruby の仕組みから Rails での定石までを整理した。
@ で始まる変数は そのオブジェクト(インスタンス)だけが持つ箱。同じクラスから作った別のインスタンスとは混ざらない。new し直すので、@current_user はリクエストごとに独立する。クラス変数(@@)にすると全リクエストで共有されて事故る。initialize / before_action / メモ化のどれかの形に収める。class Counter
def increment
@count ||= 0 # このオブジェクト専用の値
@count += 1
end
end
a = Counter.new
b = Counter.new
a.instance_variables # => [] 作った直後は @count という箱すらない
a.increment # => 1 @count が nil なので 0 を入れ、+1
a.increment # => 2 同じオブジェクトなので値が残る
b.increment # => 1 別のオブジェクトなので 0 から始まる
p a # => #<Counter:0x...658 @count=2>
p b # => #<Counter:0x...630 @count=1>
クラスは設計図、Counter.new はその設計図から作った実物(インスタンス)。
インスタンス変数は、実物の一つひとつに付いている個別の箱。
ポイントは「複数作れる」ことではなく、作ったものどうしの状態が独立していること。
# ローカル変数:メソッドを抜けるたびに消える
def increment
count = 0
count += 1
end
l.increment, l.increment # => 1, 1 毎回リセット
# インスタンス変数:オブジェクトごとに残る
a.increment, a.increment, b.increment # => 1, 2, 1 a と b は別々に数える
# クラス変数(@@):全インスタンスで1つを共有する
@@count += 1
x.increment, x.increment, y.increment # => 1, 2, 3 y が x の続きから数える
| 種類 | 書き方 | 値が残る期間 | 共有される範囲 |
|---|---|---|---|
| ローカル変数 | count |
メソッドが終わるまで | そのメソッド呼び出しの中だけ |
| インスタンス変数 | @count |
オブジェクトが存在する間 | そのオブジェクトだけ |
| クラス変数 | @@count |
アプリが動いている間 | そのクラスの全インスタンス |
名前は「どこに属するか」を表している。インスタンスに属するからインスタンス変数。
@foo を参照しても NameError にならず nil が返る。タイプミスに気づきにくい。attr_reader でゲッターを定義する(→ attr_accessorが定義するゲッターとセッター(user= はメソッド名))。@x を書くと self はクラス自身なので、クラスというオブジェクトに属する「クラスインスタンス変数」になる。これは実質全体で共有される。class ApiController < ApplicationController
before_action :authenticate
before_action :authorize
def execute
result = Schema.execute(query, context: { current_user: @current_user })
render json: result
end
private
def authenticate
@current_user = AuthHelper.find_user_from_token!(request.headers["Authorization"])
end
def authorize
head :unauthorized if @current_user.blank?
end
end
authenticate で入れた @current_user を、後続の authorize と execute が読む。
Rails はリクエストごとにコントローラーのインスタンスを新しく作るので、この値は そのリクエストの間だけ 有効。
flowchart LR
ReqA["あおい のリクエスト"] --> CtrlA["ApiController.new<br/>@current_user = あおい"]
ReqB["ひかる のリクエスト"] --> CtrlB["ApiController.new<br/>@current_user = ひかる"]
CtrlA -. 別の箱なので混ざらない .- CtrlB
コントローラーやメーラーでセットしたインスタンス変数は、対応する .erb からそのまま参照できる。これは Rails の仕組み。
# app/mailers/order_mailer.rb
class OrderMailer < ApplicationMailer
def confirmation(order)
@order = order
@coupon = order.coupon
mail(to: order.user.email, subject: "ご注文ありがとうございます")
end
end
<%# app/views/order_mailer/confirmation.html.erb %>
<p><%= @order.user.name %> 様</p>
<% if @coupon.present? %>
<p>クーポン <%= @coupon.code %> が適用されました</p>
<% end %>
もっともよく見かけるパターン。
class OrderForm
def now
@now ||= Time.current # 初回だけ計算し、2回目以降は同じ値を返す
end
end
@x ||= 計算 は「@x が nil か false なら計算して代入し、そうでなければそのまま返す」。
バリデーションと保存処理で「現在時刻」がずれないように値を固定する、といった用途で使う。
どのメソッドで代入しても、その時点からオブジェクトの持ち物になり、他のメソッドから読める。宣言はいらない。
class Order
def initialize(price)
@price = price # new したときに作られる
end
def apply_coupon
@discount = 500 # このメソッドを呼んだときに初めて作られる
end
def total
@price - @discount.to_i # nil.to_i は 0 なので未代入でも計算できる
end
end
o = Order.new(3000)
o.total # => 3000 まだ @discount は存在しない(nil)
o.apply_coupon
o.total # => 2500 apply_coupon で作った @discount を total が読めた
o.instance_variables # => [:@price, :@discount] あとから箱が増えている
def total
@price - @discount # apply_coupon を呼んでいないと nil
end
Order.new(3000).total # => TypeError: nil can't be coerced into Integer
「あのメソッドを先に呼んでおかないと動かない」という依存関係がコード上に見えないのが、一番のリスク。
この順番依存を避けるため、実務ではほぼ次のどれかに収める。
| 形 | 作る場所 | 順番が保証される理由 | 例 |
|---|---|---|---|
| ① 生成時に必ず入れる | initialize |
new した時点で必ず値がある |
上の @price |
| ② 前段で入れ、後段で読む | before_action など |
呼ぶ順番をフレームワークが保証している | (A) の @current_user |
| ③ 読むメソッドの中で作る(メモ化) | `def now; @now | = Time.current; end` |
sequenceDiagram
participant Rails
participant C as ApiController
Rails->>C: new
Rails->>C: authenticate(before_action)
Note over C: @current_user を代入
Rails->>C: authorize(before_action)
Note over C: @current_user.blank? を確認
Rails->>C: execute
Note over C: @current_user を context に詰める
②でも未ログインなら @current_user は nil のままになり得るので、authorize 側で nil を明示的にチェックしている。
| 落とし穴 | 内容 | 対処 |
|---|---|---|
| nil や false はメモ化されない | 結果が nil / false だと ||= が毎回計算し直す |
return @x if defined?(@x) のあとに @x = 計算 と書く |
| モデルでのメモ化が古くなる | @foo ||= で覚えた値は reload や属性変更後も残る |
DB の状態に依存する値をモデルでメモ化するときは注意 |
| クラスレベルに状態を持たせる | クラス直下の @x や @@x は全リクエスト・全スレッドで共有され、Puma などのマルチスレッド環境で他人のリクエストの値が混ざる |
リクエスト単位の値は ActiveSupport::CurrentAttributes(Current.user など)を使う |
| タイプミスに気づきにくい | @curent_user と書いても nil が返るだけでエラーにならない |
attr_reader 経由で読めば NoMethodError で気づける |
| GraphQL の resolver に届かない | コントローラーのインスタンス変数は resolver からは見えない | context: { current_user: @current_user } に詰め直し、resolver 側で context[:current_user] で取り出す |