Skip to content

Commit bc17eee

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

File tree

2 files changed

+9
-0
lines changed

2 files changed

+9
-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: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@ def test_to_hash
5454
assert_equal 0, h.fetch(:one)
5555
end
5656

57+
def test_deconstruct_keys
58+
ta = Rake::TaskArguments.new([:a, :b, :c], [1, 2, 3])
59+
assert_equal ta.deconstruct_keys([:a, :b]), { a: 1, b: 2 }
60+
end
61+
5762
def test_enumerable_behavior
5863
ta = Rake::TaskArguments.new([:a, :b, :c], [1, 2, 3])
5964
assert_equal [10, 20, 30], ta.map { |k, v| v * 10 }.sort

0 commit comments

Comments
 (0)