4
我想寫一個版本的assert_difference
將接受一個哈希作爲參數,這樣,而不是寫如何用ruby中的給定綁定創建塊?
assert_difference 'thing1', 1 do
assert_difference ['thing2a', 'thing2b'], 2 do
assert_difference 'thing3', -3 do
# some triple-indented code
end
end
end
我可以寫
assert_difference 'thing1' => 1, ['thing2a', 'thing2b'] => 2, 'thing3' => 3 do
# some single-indented code
end
我得儘可能
def assert_difference_with_hash_support(expression, difference = 1, message = nil, &block)
if expression.is_a? Hash
expression.each do |expr, diff|
block = lambda do
assert_difference_without_hash_support expr, diff, &block
end
end
block.call
else
assert_difference_without_hash_support(expression, difference, message, &block)
end
end
alias_method_chain :assert_difference, :hash_support
但這不起作用,因爲assert_difference在評估表達式時使用了塊的綁定。我想要做的是創造與原來綁定一個新的塊 - 像這樣:
b = block.send :binding
expression.each do |expr, diff|
block = lambda(b) do
assert_difference_without_hash_support expr, diff, &block
end
end
block.call
,但我還沒有看到創建比當前綁定以外的任何新區塊的方式。如何使用給定的綁定創建塊?