Deprecate_method.rb

This content was produced by an LLM and could include errors.

このスクリプトは非推奨メソッド警告の仕組みです。Module クラスを再オープンして deprecate を定義し、heredoc + module_eval 内で元メソッドを deprecated_xxx という別名に退避させ、本体を「標準エラーへ警告を出してから別名を呼ぶ」ラッパーへ差し替えます(対象は MyClass のインスタンスメソッド mymethod)。呼び出すと警告のうえ本来の処理が実行され、__LINE__ + 1 指定によりバックトレースの行番号も保たれます。

class Module
  def deprecate(method_name)
    module_eval <<-END, __FILE__, __LINE__ + 1
alias_method :deprecated_#{method_name}, :#{method_name}
def #{method_name}(*args, &block)
$stderr.puts "Warning: #{self}##{method_name} deprecate"
deprecated_#{method_name}(*args, &block)
end
END
  end
end
#=> :deprecate

class MyClass
  def mymethod; end
  deprecate :mymethod
end
#=> :mymethod

MyClass.new.mymethod
Warning: MyClass#mymethod deprecate
#=> nil

Ruby 4.0.6