Project

General

Profile

Actions

Feature #14313

closed

Support creating KeyError with receiver and key from Ruby

Added by kou (Kouhei Sutou) over 3 years ago. Updated over 3 years ago.

Status:
Closed
Priority:
Normal
Target version:
-
[ruby-core:84626]

Description

KeyError has readers for error details, receiver and key. They are convenient to process KeyError.

We can set receiver and key to KeyError by rb_key_err_new() in C. But we can't set them in Ruby. Because receiver and key use no @ instance variables.

How about adding KeyError#initialize that accepts receiver and key? Because KeyError is useful in pure Ruby libraries. For example, csv library uses KeyError: https://svn.ruby-lang.org/cgi-bin/viewvc.cgi/trunk/lib/csv.rb?revision=59849&view=markup#l321

def fetch(header, *varargs)
  # ...
  raise KeyError, "key not found: #{header}"
  # ...
end

I want to use KeyError for Hash like objects such as Arrow::Table in Red Arrow.

The attached patch adds KeyError#initialize that behaves as the following:

p KeyError.new.message
# => "KeyError": No change. Keep backward compatibility.

p KeyError.new("Message").message
# => "Message": No change. Keep backward compatibility.

p KeyError.new(receiver: Object.new).receiver
# => The Object instance.

p KeyError.new(key: :unknown_key).key
# => :unknown_key

key_error = KeyError.new(receiver: Object.new, key: :unknown_key)
p key_error.receiver
# => The Object instance.
p key_error.key
# => :unknown_key

key_error = KeyError.new("Message", receiver: Object.new, key: :unknown_key)
p key_error.message
# => "Message"
p key_error.receiver
# => The Object instance.
p key_error.key
# => :unknown_key

Files

key_error_new.diff (2.91 KB) key_error_new.diff kou (Kouhei Sutou), 01/04/2018 04:58 AM

Related issues

Related to Ruby master - Bug #14670: Objectで定義したmethod_missingでsuperが使えないClosedActions
Actions

Also available in: Atom PDF