Skip to content

Commit cff7664

Browse files
rgarnerhsbt
authored andcommitted
Pattern matching support for arguments
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.
1 parent a4454e6 commit cff7664

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

lib/rake/task_arguments.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@ def fetch(*args, &block)
9494
@hash.fetch(*args, &block)
9595
end
9696

97+
def deconstruct_keys(keys)
98+
@hash.slice(*keys)
99+
end
100+
97101
protected
98102

99103
def lookup(name) # :nodoc:

test/test_rake_task_arguments.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ def test_to_hash
5454
assert_equal 0, h.fetch(:one)
5555
end
5656

57+
def test_deconstruct_keys
58+
omit "No stable pattern matching until Ruby 3.1 (testing #{RUBY_VERSION})" if RUBY_VERSION < "3.1"
59+
60+
ta = Rake::TaskArguments.new([:a, :b, :c], [1, 2, 3])
61+
assert_equal ta.deconstruct_keys([:a, :b]), { a: 1, b: 2 }
62+
end
63+
5764
def test_enumerable_behavior
5865
ta = Rake::TaskArguments.new([:a, :b, :c], [1, 2, 3])
5966
assert_equal [10, 20, 30], ta.map { |k, v| v * 10 }.sort

0 commit comments

Comments
 (0)