LoginSignup
1
1

More than 5 years have passed since last update.

deprecate と宣言されたメソッドを呼び出したときに警告を出す

Last updated at Posted at 2013-06-29

出展: リファクタリング:Rubyエディション に掲載されていたコードを写経(出力されるメッセージなどは適当に変更している)。

以下のように Module クラスに deprecate メソッドを定義する。

module_ext.rb
class Module
  def deprecate(method_name)
    module_eval <<-END
      alias_method :deprecated_#{method_name}, :#{method_name}
      def #{method_name}(*args, &block)
        $stderr.puts "Warning: #{self}##{method_name} メソッドは将来的に廃止される予定のため非推奨です!!!"
        deprecated_#{method_name}(*args, &block)
      end
    END
  end
end

以下のように、非推奨(deprecate) とするメソッド名をシンボルで渡す。

hoge.rb
class Hoge
  def fuga
    puts "やほー!!!"
  end

  deprecate :fuga
end

実行結果:

hoge = Hoge.new
hoge.fuga

Warning: Hoge#fuga メソッドは将来的に廃止される予定のため非推奨です!!!
やほー!!
1
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
1
1