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

Conversation

RobinDaugherty
Copy link

@RobinDaugherty RobinDaugherty commented Dec 18, 2024

Problem

Pattern matching allows us to match the contents of primitive types and hashes.

config = {db: {user: 'admin', password: 'abc123'}}

case config
in db: {user:} # matches subhash and puts matched value in variable user
  puts "Connect with user '#{user}'"
end

But an ImmutableStruct object instance cannot currently be matched like it's a hash:

# This doesn't currently work:
UserConnection = ImmutableStruct.new(:user, :password)
DbConfig = ImmutableStruct.new(:db)

config = DbConfig.new(db: UserConnection.new(user: 'admin', password: 'abc123'))

case config
in db: {user:} # matches sub-object and puts matched value in variable user
  puts "Connect with user '#{user}'"
end

Solution

I added a deconstruct_keys instance method. (Here is the doc)[https://docs.ruby-lang.org/en/master/syntax/pattern_matching_rdoc.html#label-Matching+non-primitive+objects-3A+deconstruct+and+deconstruct_keys]

This method is called when the pattern above is being matched: for the UserConnection it's called with the argument [:user], and it returns the hash {user: 'admin'}. Ruby can then use this value to match against and assign within the matching block.


This can also be achieved by defining the method in each ImmutableStruct object declaration:

UserConnection = ImmutableStruct.new(:user, :password) do
  def deconstruct_keys(keys)
    to_h.slice(*keys)
  end
end

but copy+pasting that into every instance isn't great.

@RobinDaugherty RobinDaugherty requested a review from a team as a code owner December 18, 2024 14:00
@RobinDaugherty RobinDaugherty changed the title Support pattern matching on instance keys Support pattern matching on instances Dec 18, 2024
@@ -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.

@soulcutter
Copy link
Contributor

Thanks for this contribution! Supporting pattern matching is an excellent enhancement.

I will say that usage of this gem has declined given Ruby's Data implementation. https://docs.ruby-lang.org/en/master/Data.html which does support pattern matching.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants