Skip to content

Commit

Permalink
Fix keyword arguments to Struct.new
Browse files Browse the repository at this point in the history
  • Loading branch information
herwinw committed Dec 18, 2024
1 parent f23452a commit b943e2b
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 15 deletions.
4 changes: 1 addition & 3 deletions spec/core/struct/new_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,7 @@ def obj.to_str() "Foo" end

ruby_version_is "3.2" do
it "raises a TypeError if passed a Hash with an unknown key" do
NATFIXME 'it raises a TypeError if passed a Hash with an unknown key', exception: SpecFailedException do
-> { Struct.new(:animal, { name: 'chris' }) }.should raise_error(TypeError)
end
-> { Struct.new(:animal, { name: 'chris' }) }.should raise_error(TypeError)
end
end

Expand Down
15 changes: 3 additions & 12 deletions src/struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class << self
alias [] new
end

def self.new(*attrs, &block)
def self.new(*attrs, keyword_init: nil, &block)
duplicates = attrs.tally.find { |_, size| size > 1 }
unless duplicates.nil?
raise ArgumentError, "duplicate member: #{duplicates.first}"
Expand All @@ -17,15 +17,6 @@ def self.new(*attrs, &block)
attrs.shift
end

if attrs.last.is_a?(Hash)
options = attrs.pop
unknown_keys = options.keys.difference([:keyword_init])
if unknown_keys.any?
raise ArgumentError, "unknown keyword: #{unknown_keys.map(&:inspect).join(', ')}"
end
else
options = {}
end
result = Class.new(Struct) do
include Enumerable

Expand All @@ -38,7 +29,7 @@ def self.new(*attrs, &block)
end
alias_method :size, :length

if options[:keyword_init]
if keyword_init
define_method :initialize do |args = {}|
unless args.is_a?(Hash)
raise ArgumentError, "wrong number of arguments (given #{args.size}, expected 0)"
Expand All @@ -61,7 +52,7 @@ def self.new(*attrs, &block)
end

self.class.define_method :keyword_init? do
options[:keyword_init] ? true : options[:keyword_init]
keyword_init ? true : keyword_init
end

define_method :each do
Expand Down

0 comments on commit b943e2b

Please sign in to comment.