0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ひとりアドベントカレンダーAdvent Calendar 2024

Day 12

【Rails】Object#withの使い方

Last updated at Posted at 2024-12-11

紹介

Object#withが便利だったので紹介

こういうクラスを用意する

class Player
  attr_accessor :number

  def initialize(number:)
    self.number = number
  end

  def puts_number
    puts number
  end
end

このようなクラスで、puts_numberメソッドだけ動作を確認したい時がある
前後に処理がある中で動作確認をするとき、動作確認後は値を戻したい場合にはこういうコードになる

player = Player.new(number: 2)

begin
  player.number = 3
  player.puts_number
ensure
  player.number = 2
end

player.puts_number

実行すると出力は

3
2

のようになる

これはこれでいいのだが、便利なメソッドがある

それがこれ

player = Player.new(number: 2)

player.with(number: 3) do
  player.puts_number
end

player.puts_number

実行すると先ほどと同じく

3
2

となる

Object#withの内部実装もわかりやすい

  def with(**attributes)
    old_values = {}
    begin
      attributes.each do |key, value|
        old_values[key] = public_send(key)
        public_send("#{key}=", value)
      end
      yield
    ensure
      old_values.each do |key, old_value|
        public_send("#{key}=", old_value)
      end
    end
  end

最初のコードとほぼ同じ
これからはこれを使っていこう

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?