Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support pattern matching on instances #70

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/immutable-struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ def merge(new_attrs)
end
(attribute_values + [self.class]).hash
end

def deconstruct_keys(keys)
to_h.slice(*keys)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From the ruby docs:

keys are passed to deconstruct_keys to provide a room for optimization in the matched class: if calculating a full hash representation is expensive, one may calculate only the necessary subhash

I don't think we need or want to slice a subhash here - it's actually less optimized that way. There's also a bug this introduces, since pattern matching with "any key" (e.g. **rest) will pass keys = nil and expects to get the entire hash, but slice(*nil) # => { }. A test could be written for this case which would fail given this implementation.

https://zverok.space/blog/2022-12-20-pattern-matching.html#dont-forget-about-the-any-key-option recommends not optimizing this, and just returning the full hash in most cases, and I think this is one of those cases. Note: this would reflect a change in the returns a hash with the specified keys test.

end
end
klass.class_exec(&block) unless block.nil?

Expand Down
20 changes: 20 additions & 0 deletions spec/immutable_struct_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,26 @@ def location_near?(other_location)
end
end

describe "#deconstruct_keys" do
it "returns a hash with the specified keys" do
klass = ImmutableStruct.new(:a, :b, :c)
instance = klass.new(a: 1, b: 2, c: 3)
expect(instance.deconstruct_keys([:a, :c])).to eq({ a: 1, c: 3 })
end

it "allows an instance to be used with pattern matching" do
klass = ImmutableStruct.new(:a, :b, :c)
instance = klass.new(a: 1, b: 2, c: 3)
expect {
case instance
in { a: 1 }
# good!
end
# a NoMatchingPatternError would be raised if the pattern didn't match
}.not_to raise_error
end
end

describe "merge" do
it "returns a new object as a result of merging attributes" do
klass = ImmutableStruct.new(:food, :snacks, :butter)
Expand Down