我正在尝试编写一个 assert_difference
版本,它将接受哈希作为参数,这样就不用编写
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 在计算表达式时使用 block 的绑定(bind)。我想做的是用原始绑定(bind)创建一个新 block ——像这样:
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
但我还没有看到用当前绑定(bind)以外的任何东西创建新 block 的方法。如何创建具有给定绑定(bind)的 block ?
最佳答案
也许我遗漏了什么,但我认为您正在尝试使用 ruby 的非常复杂的功能,而它们对于解决您的问题是不必要的。
我的解决方案是:
def assert_hash(hash, &block)
if hash.length > 1
assert_difference(*hash.shift) do
assert_hash(hash, &block)
end
else
assert_difference(*hash.first, &block)
end
end
当然它缺少别名,但这不是重点。
编辑:
关于创建带有自定义绑定(bind)的 block ,答案是:不。但是您可以调用具有不同绑定(bind)的代码块,或者使用 binding
方法捕获,或者仅通过提供与其相关的绑定(bind)的对象。
您可以为此目的使用 eval
(它接受 Binding 对象作为第二个参数)或更好的 instance_eval
、class_eval
、instance_exec
和 class_exec
。您可以在 Jay Fields' Thoughts blog entry 开始挖掘.
关于ruby - 如何在 ruby 中创建具有给定绑定(bind)的 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6622197/