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`. 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 authored and hsbt committed Mar 15, 2024
1 parent 1494e38 commit bc17eee
Show file tree
Hide file tree
Showing 2 changed files with 9 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
5 changes: 5 additions & 0 deletions test/test_rake_task_arguments.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ def test_to_hash
assert_equal 0, h.fetch(:one)
end

def test_deconstruct_keys
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 bc17eee

Please sign in to comment.