膨大な数の拡張メソッドが収録されているRuby Facets。現時点で日本語のドキュメントが存在しないため、普通は英語のドキュメントを解読していくことになるのですが、メソッドを一つ一つ解読していくのは大変です。そこでこのblogでは、私的なメモも兼ねて、Ruby Facetsに収録されたライブラリを日本語で解説していきます。
第4回は例外(Exception)クラスを拡張する facets/exception です。Ruby Facets 2.8.1に準拠しています。
駆け足紹介(クイックツアー)
require 'facets/exception'
# detail: エラーの詳細を表示する
begin
wrong_name_method
rescue NameError
puts $!.detail
end
# 出力:
# undefined local variable or method `wrong_name_method' for main:Object
# exception-tour.rb:5
# LOGGED FROM: exception-tour.rb:7
# Exception.suppress: 指定したクラスに属する例外を抑制する
Exception.suppress(NameError, ArgumentError) do
wrong_name_method
end
puts "NameError is suppressed."
クラスメソッド
Exception.suppress(*exception_classes) { ... }
ブロック内において、指定したクラスの例外が発生しても、インタープリタの実行が終了されないようにするる。
引数には1つ以上の例外クラスを与える。ブロック実行中に何らかの例外が発生したとき、その例外が引数で指定した例外クラスのどれかに属している(kind_of? 判定で true になる)なら、そのままブロックを抜ける。
require 'facets/exception/suppress'
wrong_name_method
# undefined local variable or method `wrong_name_method' for main:Object (NameError)
Exception.suppress(NameError, ArgumentError) do
wrong_name_method
end
# 何も起きない
インスタンスメソッド
detail
その例外の詳細を表す文字列を返す。バックトレースや呼び出し元などの情報を含んでおり、message や to_s よりも詳しい情報を得ることができる。
require 'facets/exception/detail'
begin
wrong_name_method
rescue
puts "-- Detail ----------------"
puts $!.detail
end
-- Detail ----------------
undefined local variable or method `wrong_name_method' for main:Object
exception-detail.rb:4
LOGGED FROM: exception-detail.rb:7
raised? { ... }
ブロックの実行時に例外が発生するかどうかを判定するメソッドのようだが、現時点(Ruby Facets 2.8.1)では正常に動作しない。ソースコードを見る限り、rescue 節に例外クラスでない self を渡そうとしているため、もともと動作するはずがないメソッドのようだ。
class Exception
# Does a block raise an a given +exception+.
#
def self.raised? #:yeild:
begin
yield
false
rescue self
true
end
end
end
1 : Somatrope 15 IU
让我印象深刻,我不用说了。我真的不经常遇到的每一个教育性和娱乐性的博客,并让我告诉你,你有腹背受敌一针见血。您的概念是突出的困难是一回事,没有足够的人都讲智能化约。我很幸福,就这样迷迷糊糊,我整个这在我寻求。
このコメントを編集/削除