我正在尝试将一些数据作为一个块传递给一些外部 API。让它接受额外的参数会很麻烦。如果是javascript
,我可能会这样:
var callback = function() {
// do something
}
callback['__someData'] = options;
someExternalAPI(callback);
Ruby可以做到这一点吗?或者我应该如何将一些数据与块相关联?
不确定对问题的编辑是否正确。首先,如果可能的话,我想专门传递一些数据和一个块。不确定是否是这样。并且可能唯一的方法ruby
是将一些数据作为块传递。
此外,这里可能会提供一些有用的信息。
好的,展示整个画面可能是有意义的。我正在努力适应webmock
我的需求。我有一个函数,它检查请求的参数(无论是POST
还是GET
)是否匹配指定的条件:
def check_params params, options
options.all? do |k,v|
return true unless k.is_a? String
case v
when Hash
return false unless params[k]
int_methods = ['<', '<=', '>', '>=']
v1 = int_methods.include?(v.first[0]) ? params[k].to_i : params[k]
v2 = int_methods.include?(v.first[0]) \
? v.first[1].to_i : v.first[1].to_s
v1.send(v.first[0], v2)
when TrueClass, FalseClass
v ^ ! params.key?(k)
else
params[k] == v.to_s
end
end
end
它并不完美,但目前足以满足我的特殊需求。我这样称呼它:
stub_request(:post, 'http://example.com/')
.with { |request|
check_params Rack::Utils.parse_query(request.body), options
}
事情通常是我看不到输出with block
条件的明智方法。但在我的特殊情况下,可以只输出options
哈希。而不是这个:
registered request stubs:
stub_request(:post, "http://example.com")
有这个:
stub_request(:post, "http://example.com").
with(block: {"year"=>2015})
这就是我想要做的。