Project

General

Profile

Feature #15222

Add a way to distinguish between Struct classes with and without keyword initializer

Added by pluff (Pavel Shutsin) 6 days ago. Updated 6 days ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:89369]

Description

With Ruby 2.5.0 Struct subclasses can have different initialize arguments list based on keyword_init option. However, there is no way in Ruby to distinguish Structs with keyword arguments syntax and without.

I propose a class method keyword_init? that will allow developers to understand if given structure has keyword based initializer or not.

Example use case for serialization:

Foo = Struct.new(:foo, keyword_init: true)
Bar = Struct.new(:bar)

def dump_and_load_struct(object)
  serialized = object.to_h
  object.class.new(object.class.keyword_init? ? serialized : serialized.values)
end

dump_and_load_struct(Foo.new(foo: 1)) # #<struct Foo foo=1>
dump_and_load_struct(Bar.new(2)) # #<struct Bar bar=1>

An issue that might be related: https://bugs.ruby-lang.org/issues/14314


Related issues

Related to Ruby trunk - Feature #11925: Struct construction with kwargsClosed

History

#1 Updated by k0kubun (Takashi Kokubun) 6 days ago

  • Related to Bug #14314: Marshalling broken in Ruby 2.5.0 for Structs with keyword_init: true added

#2 Updated by k0kubun (Takashi Kokubun) 6 days ago

  • Related to deleted (Bug #14314: Marshalling broken in Ruby 2.5.0 for Structs with keyword_init: true)

#3 Updated by k0kubun (Takashi Kokubun) 6 days ago

#4 [ruby-core:89370] Updated by k0kubun (Takashi Kokubun) 6 days ago

This would be helpful for implementing custom deserializer of Struct.

Note: If you need to support Ruby 2.5, you would need to do object.class.inspect.end_with?('(keyword_init: true)').

Also available in: Atom PDF