Skip to content

Commit

Permalink
Pattern matching support for arguments
Browse files Browse the repository at this point in the history
Implement `Rake::TaskArguments#deconstruct_keys` for use in Ruby 3.1
and up. This means in an idiomatic rake task we can use rightward
assignment to say:

```
task :get, %i[tenant id] do |_t, args|
  args => {tenant:, id:}
  ...
end
```

... and omit the `.to_h` from `args`, raising `NoMatchingPatternError`
if either of the two params is absent from the task args.
  • Loading branch information
rgarner committed Apr 2, 2024
1 parent 675498c commit cbd2e35
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/rake/task_arguments.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ def fetch(*args, &block)
@hash.fetch(*args, &block)
end

def deconstruct_keys(keys)
@hash.slice(*keys)
end

protected

def lookup(name) # :nodoc:
Expand Down
7 changes: 7 additions & 0 deletions test/test_rake_task_arguments.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ def test_to_hash
assert_equal 0, h.fetch(:one)
end

def test_deconstruct_keys
omit "No stable pattern matching until Ruby 3.1 (testing #{RUBY_VERSION})" if RUBY_VERSION < "3.1"

ta = Rake::TaskArguments.new([:a, :b, :c], [1, 2, 3])
assert_equal ta.deconstruct_keys([:a, :b]), { a: 1, b: 2 }
end

def test_enumerable_behavior
ta = Rake::TaskArguments.new([:a, :b, :c], [1, 2, 3])
assert_equal [10, 20, 30], ta.map { |k, v| v * 10 }.sort
Expand Down

0 comments on commit cbd2e35

Please sign in to comment.