Ruby Issue Tracking System: Issueshttps://bugs.ruby-lang.org/https://bugs.ruby-lang.org/favicon.ico?17113305112018-10-11T13:01:48ZRuby Issue Tracking System
Redmine Ruby master - Feature #15222 (Open): Add a way to distinguish between Struct classes with and wit...https://bugs.ruby-lang.org/issues/152222018-10-11T13:01:48Zpluff (Pavel Shutsin)
<p>With Ruby 2.5.0 Struct subclasses can have different <code>initialize</code> arguments list based on <code>keyword_init</code> option. However, there is no way in Ruby to distinguish Structs with keyword arguments syntax and without.</p>
<p>I propose a class method <code>keyword_init?</code> that will allow developers to understand if given structure has keyword based initializer or not.</p>
<p>Example use case for serialization:</p>
<pre><code>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>
</code></pre>
<p>An issue that might be related: <a href="https://bugs.ruby-lang.org/issues/14314" class="external">https://bugs.ruby-lang.org/issues/14314</a></p>