在ruby中,您可以像这样调用远程api。
def get_remote_date
Net::HTTP.get('example.com', '/index.json')
end如果你使用gem install vcr,你可以做到这一点
def get_remote_date
VCR.use_cassette("cassette_001") do
Net::HTTP.get('example.com', '/index.json')
end
end当远程api昂贵时,Vcr录制/回放在开发过程中会有所帮助。是否使用vcr应该是可选的,由函数的第一个参数指示:
def get_remote_date(should_use_vcr)
VCR.use_cassette("cassette_001") do
Net::HTTP.get('example.com', '/index.json')
end
end我的问题是,如何重写该方法,以使“块包装”/ "VCR.use_cassette("cassette_001") do“以should_use_vcr局部变量的布尔值为条件。
我能做到
def get_remote_date(should_use_vcr)
if conditional here
VCR.use_cassette("cassette_001") do
Net::HTTP.get('example.com', '/index.json')
end
else
Net::HTTP.get('example.com', '/index.json')
end
end但是对于包含"Net::HTTP.get(“外加十几行代码)的复杂方法来说,有太多的重复代码,所以要寻找一种更整洁的方法。
发布于 2019-10-16 06:04:09
您可以尝试使用以下方法:
def get_remote_date
record_request { Net::HTTP.get('example.com', '/index.json') }
end
def record_request(&request)
ENV['RECORD_REQUEST'] ? VCR.use_cassette("cassette_001", &request) : request.call
end这是一个很好的article,它解释了&block (与号参数)的含义以及它与yield关键字的关系。
发布于 2019-10-16 22:10:21
图示了基于产量的解决方案,
def maybe_cache_http_requests(cassette)
if ENV['CACHE_HTTP_REQUESTS'] == "1"
require 'vcr'
VCR.configure do |config|
config.cassette_library_dir = "vcr_cassettes"
config.hook_into :webmock
end
VCR.use_cassette(cassette) do
yield
end
else
yield
end
end发布于 2019-10-15 22:49:23
您可以将重复的代码放入一个方法中,然后调用包装在VCR do块中或没有VCR的方法。
https://stackoverflow.com/questions/58397185
复制相似问题