RubyアプリケーションでException依存関係を明確に定義する方法を探します。それは存在しません:Ruby:値でクラスを動的に作成する
def error_class(superclass, http_code_value)
Class.new(superclass) do
def http_code
http_code_value
end
end
end
class AppError < StandardError
def to_s
"Here is my code: #{http_code}"
end
# other methods ...
end
# Clean error tree build
ClientError = error_class AppError, 400
ServerError = error_class AppError, 500
TeapotError = error_class ClientError, 418
# and so on ...
puts "client #{ClientError.new}" # client Here is my code: 400
puts "server #{ServerError.new}" # server Here is my code: 500
puts "teapot #{TeapotError.new}" # teapot Here is my code: 418
ここでの問題は、パラメータ_http_code
がクラスのコンテキストで評価されている。ここで は、私は(次の例では動作しません)に接近したいものです。
evalに頼らずに達成できる方法はありますか?
def error_class(_superclass, _http_code)
Class.new(_superclass) do
define_method(:http_code) do
_http_code
end
end
end
define_method
を使用して、それは彼らが、デフォルトでは、正しいコンテキストで作成されます。
通常、引数の前にアンダースコアを付けて、この引数を使用しないことを指定します。 – engineersmnky
私は同意します。この例では、http_code名と矛盾しないようにアンダースコアを追加し、無限再帰がないことを100%確信しています。しかし、私は別の名前でそれを改名するべきだった。 – firetonton